Search code examples
javabytebufferunsigned-integer

Inserting unsigned integer value into bytebuffer, maintaining binary representation


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?


Solution

  • 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).