1

I'm trying to put the following binary representation into a bytebuffer for 4 bytes. But since Java doesn't do unsigned, I'm having trouble: 11111111000000001111111100000000

ByteBuffer bb = ByteBuffer.allocate(8);

bb.putInt(Integer.parseInt("11111111000000001111111100000000", 2));
//throws numberformatexception

Negating the most significant bit seems to change the binary string value because of how two's compliment works:

bb.putInt(Integer.parseInt("-1111111000000001111111100000000", 2));
System.out.println(Integer.toBinaryString(bb.getInt(0)));
//prints 10000000111111110000000100000000

It's important that the value is in this binary format exactly because later it will be treated as an unsigned int. How should I be adding the value (and future values that start with 1) to the bytebuffer?

3 Answers 3

1

Just parse it as a long first, and cast the result:

int value = (int) Long.parseLong("11111111000000001111111100000000", 2);

That handles the fact that int runs out of space, because there's plenty of room in a long. After casting, the value will end up as a negative int, but that's fine - it'll end up in the byte buffer appropriately.

EDIT: As noted in comments, in Java 8 you can use Integer.parseUnsignedInt("...", 2).

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

2 Comments

Thanks, Jon Skeet! Exactly what I was looking for.
For what it's worth, Java8 adds Integer.parseUnsignedInt, which would also work.
1

You can also use Guava's UnsignedInts.parseUnsignedInt(String string, int radix) and UnsignedInts.toString(int x,int radix) methods:

int v = UnsignedInts.parseUnsignedInt("11111111000000001111111100000000", 2);
System.out.println(UnsignedInts.toString(v, 2));

Comments

0

try this

    bb.putInt((int)Long.parseLong("11111111000000001111111100000000", 2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.