-1

I am working with java.nio in Java 8. I receive an unsigned int inside the buffer and i want to save it as such, but i get a negative number.

final int shouldBePositive = buffer.getInt();

and shouldBePositive is negative.

Is there a way to work around the fact Java doesn't have unsigned int type?

slashms
  • 928
  • 9
  • 26

1 Answers1

2

Aside from simply living with this, you could always use a long type, and restrict your usage to the least significant 32 bits.

That will model a 32 bit unsigned integral type.

For longer unsigned types, you'll need to base a solution on java.math.BigInteger.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I have other scenarios for unsigned long as well. So this is still doesn't help me. – slashms Oct 05 '16 at 10:27
  • In that case use `Long.toUnsignedString()` as Alex suggested. If nothing else works for you, you will have to develop your own method; you can always get the raw (signed) bytes from the `ByteBuffer`. – Ole V.V. Oct 05 '16 at 10:57