Java print binary number using bit-wise operator
Posted
by user69514
on Stack Overflow
See other posts from Stack Overflow
or by user69514
Published on 2010-05-06T20:11:25Z
Indexed on
2010/05/06
20:18 UTC
Read the original article
Hit count: 161
Hi I am creating a method that will take a number and print it along with its binary representation. The problems is that my method prints all 0's for any positive number, and all 1's for any negative number
private static void display( int number ){
System.out.print(number + "\t");
int mask = 1 << 31;
for(int i=1; i<=32; i++) {
if( (mask & number) != 0 )
System.out.print(1);
else
System.out.print(0);
if( (i % 4) == 0 )
System.out.print(" ");
}
}
© Stack Overflow or respective owner