Declaring an unsigned int in Java
Solution 1:
Java does not have a datatype for unsigned integers.
You can define a long
instead of an int
if you need to store large values.
You can also use a signed integer as if it were unsigned. The benefit of two's complement representation is that most operations (such as addition, subtraction, multiplication, and left shift) are identical on a binary level for signed and unsigned integers. A few operations (division, right shift, comparison, and casting), however, are different. As of Java SE 8, new methods in the Integer
class allow you to fully use the int
data type to perform unsigned arithmetic:
In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 2^32-1. Use the Integer class to use int data type as an unsigned integer. Static methods like
compareUnsigned
,divideUnsigned
etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
Note that int
variables are still signed when declared but unsigned arithmetic is now possible by using those methods in the Integer
class.
Solution 2:
Whether a value in an int is signed or unsigned depends on how the bits are interpreted - Java interprets bits as a signed value (it doesn't have unsigned primitives).
If you have an int that you want to interpret as an unsigned value (e.g. you read an int from a DataInputStream
that you know should be interpreted as an unsigned value) then you can do the following trick.
int fourBytesIJustRead = someObject.getInt();
long unsignedValue = fourBytesIJustRead & 0xffffffffL;
Note, that it is important that the hex literal is a long literal, not an int literal - hence the 'L' at the end.
Solution 3:
We needed unsigned numbers to model MySQL's unsigned TINYINT
, SMALLINT
, INT
, BIGINT
in jOOQ, which is why we have created jOOU, a minimalistic library offering wrapper types for unsigned integer numbers in Java. Example:
import static org.joou.Unsigned.*;
// and then...
UByte b = ubyte(1);
UShort s = ushort(1);
UInteger i = uint(1);
ULong l = ulong(1);
All of these types extend java.lang.Number
and can be converted into higher-order primitive types and BigInteger
. Hope this helps.
(Disclaimer: I work for the company behind these libraries)
Solution 4:
For unsigned numbers you can use these classes from Guava library:
- UnsignedInteger
- UnsignedLong
They support various operations:
- plus
- minus
- times
- mod
- dividedBy
The thing that seems missing at the moment are byte shift operators. If you need those you can use BigInteger from Java.
Solution 5:
Perhaps this is what you meant?
long getUnsigned(int signed) {
return signed >= 0 ? signed : 2 * (long) Integer.MAX_VALUE + 2 + signed;
}
-
getUnsigned(0)
→ 0 -
getUnsigned(1)
→ 1 -
getUnsigned(Integer.MAX_VALUE)
→ 2147483647 -
getUnsigned(Integer.MIN_VALUE)
→ 2147483648 -
getUnsigned(Integer.MIN_VALUE + 1)
→ 2147483649