Allen Allen - 16 days ago 5
Java Question

How to convert byte to binary in java?

I have attempted convert from 10000101 to -123 by code

byte sum = (byte) (Integer.valueOf(10000101, 2) & 0xffff) ";


now I don't know how to convert back from -123 to 10000101.

Any suggestions about using java API to do conversion?

Answer

Expanding a bit the David Wallace comment, you can do it with this code:

    String fromByteToString = String.format("%8s", Integer.toBinaryString(sum & 0xFF)).replace(' ', '0');
    System.out.println(fromByteToString);

with sum & 0xFF you do the bitwise AND operation:

-123 = 11111111111111111111111110000101
0xFF = 00000000000000000000000011111111
res. = 00000000000000000000000010000101

Note that the replace(' ', '0') is not a must in this case because the binary result string starts (10000101) with 1.

Comments