Decimal to binary in C
Decimal to binary in C programming: C program to convert an integer from decimal number system (base-10) to binary number system (base-2). Size of an integer is assumed to be 32 bits. We will use the bitwise operator "AND" to perform the desired task. We right shift the original number by 31, 30, 29, ..., 1, 0 bits using a for loop and bitwise AND the number obtained with 1(one), if the result is 1, then that bit is 1 otherwise it is 0 (zero).
C program to convert Decimal in to Binary
#include <stdio.h>
#include<conio.h>
void main()
{
int n, c, k;
{
int n, c, k;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("1");
else
printf("0");
}
printf("\n");
getch();
}
}
C code to store decimal to binary conversion in a string
#include<stdio.h>
#include<stdlib.h>
#include<stdlib.h>
#include<conio.h>
char *decimal_to_binary(int);
void main()
{
int n, c, k;
char *pointer;
printf("Enter an integer in decimal number system\n");
scanf("%d",&n);
pointer = decimal_to_binary(n);
printf("Binary string of %d is: %s\n", n, t);
free(pointer);
getch();
}
{
int n, c, k;
char *pointer;
printf("Enter an integer in decimal number system\n");
scanf("%d",&n);
pointer = decimal_to_binary(n);
printf("Binary string of %d is: %s\n", n, t);
free(pointer);
getch();
}
char *decimal_to_binary(int n)
{
int c, d, count;
char *pointer;
count = 0;
pointer = (char*)malloc(32+1);
if (pointer == NULL)
exit(EXIT_FAILURE);
for (c = 31 ; c >= 0 ; c--)
{
d = n >> c;
if (d & 1)
*(pointer+count) = 1 + '0';
else
*(pointer+count) = 0 + '0';
count++;
}
*(pointer+count) = '\0';
return pointer;
}
{
int c, d, count;
char *pointer;
count = 0;
pointer = (char*)malloc(32+1);
if (pointer == NULL)
exit(EXIT_FAILURE);
for (c = 31 ; c >= 0 ; c--)
{
d = n >> c;
if (d & 1)
*(pointer+count) = 1 + '0';
else
*(pointer+count) = 0 + '0';
count++;
}
*(pointer+count) = '\0';
return pointer;
}
No comments:
Post a Comment