Is there a Java library for unsigned number type wrappers?
When I needed this functionality inside of jOOQ, I haven't found anything like it, so I rolled my own Open Source library that I call jOOU (U for Unsigned):
http://github.com/jOOQ/jOOU
I understand that some may think this is overkill, but I'd really like to have precisely those wrappers wrapping what other languages call ubyte
, ushort
, uint
, ulong
. Hopefully with Valhalla, those wrappers can be turned into value types.
Of course, contributions to the arithmetics / bitwise operation implementations are very welcome!
There are some reasons why nobody created these wrappers in the way you want.
- Performance
- Garbage collector overhead
- no autoboxing / unboxing
- bad / useless interface.
- easier ways to deal with it exists
The first four points are demonstrated by a small C example:
unsigned int x=42, y, m=5, t=18;
y = x * m + t;
This would be translated into:
UInteger m = new UInteger(5);
UInteger t = new UInteger(18);
UInteger x = new UInteger(42);
UInteger y = x.multiplyBy(m);
y = y.add(t);
Several wrapper objects must be created, multiplyBy
and add
will generate some more. This will put quite some burden on the garbage collector if many calculations are done this way. The wrapping and unwrapping will also eat up your CPUs for nothing.
That even simple arithmetic is a PITA to write or read is also obvious.
For the same reasons NOBODY does arithmetic using the signed wrapper types.
All this is unnecessary if you do the calculations using the next-bigger signed type and cut off the upper part like this:
long x=42, y, m=5, t=18
y = (x*m + t) & 0xFFFFFFFF;
Transfer between Java and a database can also be done using the next biggest signed type. And since JDBC will not create these unsigned wrapper types you would have to do exactly that by yourself only to transform the data into the unsigned wrappers thereafter.
I have done some CPU intensive data processing for myself and handled binary protocols. On these occasions I wished I had unsigned datatypes also. But emulating them in Java with wrapper types would have been more problematic than dealing with the problem directly on each single occasion.