how to get the binary values of the bytes stored in byte array

For each byte:

  • cast to int (happens in the next step via automatic widening of byte to int)
  • bitwise-AND with mask 255 to zero all but the last 8 bits
  • bitwise-OR with 256 to set the 9th bit to one, making all values exactly 9 bits long
  • invoke Integer.toBinaryString() to produce a 9-bit String
  • invoke String#substring(1) to "delete" the leading "1", leaving exactly 8 binary characters (with leading zeroes, if any, intact)

Which as code is:

byte[] bytes = "\377\0\317\tabc".getBytes();
for (byte b : bytes) {
    System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1));
}

Output of above code (always 8-bits wide):

11111111
00000000
11001111
00001001
01100001
01100010
01100011

Try Integer.toString(bytevalue, 2)

Okay, where'd toBinaryString come from? Might as well use that.

Tags:

Java