Reputation: 37
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?
Upvotes: 1
Views: 1227
Reputation: 1503220
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)
.
Upvotes: 1
Reputation: 53849
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));
Upvotes: 1
Reputation: 136102
try this
bb.putInt((int)Long.parseLong("11111111000000001111111100000000", 2));
Upvotes: 0