Java’s Long.toBinaryString(long l); come on, guys! 21 October 2009
Posted by manniwood in Uncategorized.trackback
So I’ve been doing some bit fiddling in Java, and because I don’t do a lot of bit fiddling, I want to print out the bits of longs so that I can get some feedback.
So I set up a long like so:
long someLong = 1L;
And I ask Java to show me each individual bit like so:
System.out.println(Long.toBinaryString(oldhash));
And here’s what Java outputs.
1
Thanks for printing the other 63 zeros there, Java. Great effort.
Happily, I like collecting programming books, and John W. Perry’s Advanced C Programming by Example has a nice example of printing all the bits in short ints.
It’s actually kind of cool. First what you need is a way to test each bit in a series of bits. Let’s say you have the following byte:
00000010
and you want to test its second bit (from the end). You shift that bit to the end:
byte i = 2; // i is 00000010 i >>= 1; // shift one place to get 00000001
If we were interested in the first (end-most) bit, we would harmlessly shift zero places:
i = 2; // i is 00000010 i >>= 0; // shift zero places to get 00000010
If we were interested in the third bit, we would shift two places:
i = 2; // i is 00000010 i >>= 2; // shift two places to get 00000000
You take advantage of the fact that byte’s binary representation of 1 is
00000001
so if you & together 00000001 with any other short, the first seven zeros are guaranteed to make your result have seven zeros, but the final 1 will either & together with a 1 to give you 1, telling you the last bit was set, or & together with a 0 to give you 0, telling you the last bit was not set.
// let's test the second bit: i = 2; // i is 00000010 i >>= 1; // shift one place to get 00000001 i &= 1; // i is 00000001; the second bit was set // let's test the second bit again: i = 6; // i is 00000110 i >>= 1; // shift one place to get 00000011 // 00000011 // & 00000001 // ----------- // = 00000001 i &= 1; // i is 00000001; the second bit was set
So you can write a testBit function (sorry—method; Java doesn’t have functions) that tests the i-th bit of a byte like so:
// return 1 if bitToTest-th bit of val was set,
// else return 0
byte testBit(byte val, int bitToTest) {
val >>= bitToTest;
val &= 1;
return val;
}
And you can write a toBinaryString method that uses testBit like so:
String toBinaryString(byte val) {
StringBuilder sb = new StringBuilder(8);
for (int i = 7; i >= 0; i--) {
sb.append((testBit(val, i) == 0) ? '0' : '1');
}
return sb.toString();
}
And so you can print all the zeros in your bytes:
byte i = 6; System.out.println(toBinaryString(i));
Which will print this:
00000110
instead of this:
110
Nice, eh?
please scan and share “Advanced C Programming by Example” book with your readers.
Sorry. It may be out of print, but it’s still copyrighted material. Maybe it will end up on google books?