Home > Uncategorized > Convert byte to binary representation

Convert byte to binary representation

March 16th, 2010

Use the following to show a byte value in binary representation.

/**
 * 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();
}

Uncategorized

  1. No comments yet.
  1. No trackbacks yet.