For each byte:
- discarded by
int (happens in the next step by automatically extending byte to int ) - bitwise-And with a mask of 255 to zero everything except the last 8 bits
- bitwise OR from 256 to set the 9th bit to one, making all values โโexactly 9 bits long
- invoke
Integer.toBinaryString() to create a 9-bit string - invoke
String#substring(1) to "remove the" leading "1", leaving exactly 8 binary characters (with leading zeros, if any, untouched)
What code is:
byte[] bytes = "\377\0\317\tabc".getBytes(); for (byte b : bytes) { System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1)); }
The output above the code (always 8 bits):
11111111 00000000 11001111 00001001 01100001 01100010 01100011
source share