I am trying to convert a byte value to binary for data transfer. Basically, I am sending a value like \"AC\" in binary (\"10101100\") in a byte array where \"10101100\" is a
String toBinary( byte[] bytes )
{
StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
for( int i = 0; i < Byte.SIZE * bytes.length; i++ )
sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
return sb.toString();
}
byte[] fromBinary( String s )
{
int sLen = s.length();
byte[] toReturn = new byte[(sLen + Byte.SIZE - 1) / Byte.SIZE];
char c;
for( int i = 0; i < sLen; i++ )
if( (c = s.charAt(i)) == '1' )
toReturn[i / Byte.SIZE] = (byte) (toReturn[i / Byte.SIZE] | (0x80 >>> (i % Byte.SIZE)));
else if ( c != '0' )
throw new IllegalArgumentException();
return toReturn;
}
There are some simpler ways to handle this also (assumes big endian).
Integer.parseInt(hex, 16);
Integer.parseInt(binary, 2);
and
Integer.toHexString(byte).subString((Integer.SIZE - Byte.SIZE) / 4);
Integer.toBinaryString(byte).substring(Integer.SIZE - Byte.SIZE);