Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 the bitwise manipulation?
for example:

10111001

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading