21 June 2010

Two ways to convert decimal numbers to binary strings

I'll show you two ways to convert decimal to binary.

First, the most basic way is apply the following pseudo-code:

int x
char[80] arr
do{
reminder = x%2;
arr[i] = reminder
}while (x/2 > 0);
reverse arr;


And the other is more advanced (and more simple), it use bitwise operations instead:

int x
while (x > 0){
arr[i] = ((x & 1) ? '1' : '0');
x >>=1;
}
reverse arr


and here's a C code for the last one:
 
//I am not the author of this function, I copied from the link below
void dec2binary(long i){

char* str = malloc(sizeof(long)*8*sizeof(char));

char* p = str;
while (i > 0){
*p++ = ((i & 1) ? '1' : '0');
i >>=1;
}

while( p-- != str ) /* print out the result backwards */
printf("%c",*p);

free(str);
}


please see:
http://www.daniweb.com/code/snippet216349.html
Post a Comment