Convert byte to binary representation

Use the following to show a byte value in binary representation.
[sourcecode lang=”java”]
/**
* Returns a 0 padded binary representation of the
* passed byte. For example, returns "00000001" if passed
* the byte 1. Returns "11111111" if passed byte -1.
* @param b the byte
* @return the byte in binary representation
*/
private static String toBinary(byte b){
StringBuffer sb = new StringBuffer(8);
for(int bit = 7; bit >= 0; bit–) {
if ((b & (1 << bit)) > 0)
sb.append(‘1’);
else
sb.append(‘0’);
}
return sb.toString();
}
[/sourcecode]


Posted

in

by

Tags: