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?

2
  • Are you aware of the toBinaryString method of the Integer class? Commented Nov 19, 2016 at 9:13
  • @community.. it is not the same question.. OP here asks to convert a byte to a binary string.. it's a completely different question... Commented Nov 19, 2016 at 10:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.