Wednesday, April 29, 2009

JAVA: Convesion of decimal number into binary using bitwise operators


Share at Facebook

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

I'm providing a simple JAVA code for you. Inside the function you'll find a function binaryToDecimal(), that will take a 31 bit positive integer number, and using the previously discussed method, it will just print the corresponding binary representation of the integer.

Here is the Java code for you.

public class Test{

/** main method*/
public static void main(String argv[]){
new Test().binaryToDecimal(2147483440);
}

/**
takes a positive number less than 2^31-1
prints it's binary format
*/
public void binaryToDecimal(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) != 0){
System.out.print("1");
}
// if the bit is not set, print 0
else{
System.out.print("0");
}
// shift the constant using right shift
and = and >> 1;
}
System.out.print("\n");
}
}


The output for the above code will be : 1111111111111111111111100110000

Once again for your reminder, I have used the bitwise AND(&), and bitwise Shift operator. The And (&) operator will check whether bit is set or not, and the shift operator is used to shift the bit right side one step.




2 comments:

jugal said...

very very well done...superb program...thought about it for half an hour or so...and then checked up your solution...I never would have got the logic...

Anonymous said...

Ever heard of Integer.toBinaryString()?