// decimal_2_binary.c
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
char* decimal2binary(unsigned);
int main(void){
unsigned n = 10;
printf("Enter a Positive Number? ");
scanf("%u", &n);
char *binary = decimal2binary(n);
int i;
for (i=0; i<32; i++)
printf("%i", binary[i]);
printf("\n");
return 0;
}
char* decimal2binary(unsigned x){
int size = sizeof(unsigned*)* CHAR_BIT;
char *bits = (char*) malloc(size);
char *ptr = bits;
ptr +=(size-1);
while (x > 0){
char t;
t = x &1;
x = x >>1;
*ptr--=t;
}
while ( ptr - bits >= 0){
*ptr--=0;
}
return bits;
}
14 July 2010
Decimal to Binary in C
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment