The explicit primitive Java types (i.e., bytes, short, int, and long) are all signed. But you can get around this.
To do (say) 32-bit unsigned arithmetic, just do the arithmetic, pretending that 'int' is unsigned. For example, 2**31 - 1 is the largest (signed) int value. If you add it to it, you will get -2**31 . But this bit pattern matches +2**31 if you think int is unsigned. It also works for subtraction and multiplication. (I'm not sure about the division and remainder, but most likely this is not important to you).
Comparing 32-bit unsigned values ββis a bit more complicated. For example, -1 less than +1 , but if you interpret -1 as an unsigned value, you get +2**32 - 1 , which should be greater than "+1". You can compensate by translating the inequality (I'll leave it to the reader to understand this), or by casting int values ββto long , masking them with 0xffffffffL and comparing them as longs; eg.
int u1 = ... int u2 = ... if ((((long) u1) & 0xffffffff) < (((long) u2) & 0xffffffff) {
Converting unsigned 32-bit integers to Strings is easiest to do with longs; eg.
String str = Long.toString(((long) u1) & 0xffffffffL);
Now, I will freely admit that using int to represent 32-bit unsigned values ββis complex and potentially error prone. A cleaner solution would be to use long throughout, or if your application needs 64-bit unsigned values ββto use BigInteger .
UPDATE - it looks like Java 8 will support (in the form of library methods) for handling int and long as unsigned types - see the "Unsigned Integer Arithmetic API is now in JDK 8" by Joseph Darcy @Oracle.
Stephen c
source share