javabitbitwise-operatorsbit-shiftbitwise-and

What is the proper implementation of building a string representation of the contents of a byte array?


Appending the string builder with the following method is yielding incorrect results. The bytes in the byte array do not match the '1's and '0's represented within the resulting string.

InputStream is = new FileInputStream(bout);
StringBuilder sb = new StringBuilder();
byte[] a = is.readAllBytes();
for (byte b : a) {
  for (int i = 0; i < 8; i++) {
    sb.append((b & (1 << i)) != 0 ? '1' : '0');
  }
}
is.close();

Am I improperly using bitwise manipulation?

For example:

10111001

returns

10011101


Solution

  • It's just back-to-front, the first bit you print should be the highest bit, i.e. corresponding to 2^7 (128).

    for (int i = 0; i < 8; i++) {
     sb.append((b & (128 >> i)) != 0 ? '1' : '0');
    }
    

    alternatively

    for (int i = 7; i >= 0; i--) {
     sb.append((b & (1 << i) != 0 ? '1' : '0');
    }