1

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?

progyammer
  • 1,498
  • 3
  • 17
  • 29
Allen
  • 145
  • 3
  • 10

1 Answers1

1

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.

user6904265
  • 1,938
  • 1
  • 16
  • 21