C/C++: Convesion of decimal number into binary using bitwise operators

I have already showed you how to convert a decimal number into binary using Bitwise operations at my post http://icfun.blogspot.com/2009/04/algorithm-bitwise-operation-to-convert.html

Today I'm writing a C/C++ compatible code that will accept a 31 bit positive number, and will print the corresponding binary number on console using the bitwise operations that I've mentioned my last posting. Here is the C/C++ code for you.

#include

// takes a positive number less than 2^32-1
// prints it's binary format
void binary2decimal(int dec){

// constant = 1000000000000000000000000000000
int and = 0x40000000;

// for each bit
for( int i = 1; i <= 31; i++ ){
// if the bit is set, print 1

if( dec & and ){
printf("1");
}
// if the bit is not set, print 0
else{
printf("0");
}
// shift the constant using right shift
and = and >> 1;
}
printf("\n");
}

int main(){
binary2decimal(2147483440);
return 0;
}


This Sample C/C++ code will output 1111111111111111111111100110000 on screen.

At the above code, I've just used the bitwise algorithm for the number conversion. I've used the AND (&) operation to check whether the Bit is set(1) or not (0). And using the Right shift bitwise operator, I have just shift the bit of the constant.

Once again, you can easily change the bit number from 31 to any other, as long as the number system supports to accommodate.

Comments