In the Oracle "Primitive data types" page, it mentions that Java 8 adds support for unsigned ints and longs:
int
: By default, theint
data type is a 32-bit signed two's complement integer, which has a minimum value of −231 and a maximum value of 231−1. In Java SE 8 and later, you can use theint
data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232−1. Use theInteger
class to useint
data type as an unsigned integer. See the section The Number Classes for more information. Static methods likecompareUnsigned
,divideUnsigned
etc have been added to theInteger
class to support the arithmetic operations for unsigned integers.
long
: Thelong
data type is a 64-bit two's complement integer. The signedlong
has a minimum value of −263 and a maximum value of 263−1. In Java SE 8 and later, you can use thelong
data type to represent an unsigned 64-bitlong
, which has a minimum value of 0 and a maximum value of 264−1. Use this data type when you need a range of values wider than those provided by int. TheLong
class also contains methods likecompareUnsigned
,divideUnsigned
etc to support arithmetic operations for unsignedlong
.
However, I find no way to declare an unsigned long or integer. The following code, for example, gives a compiler error message of "the literal is out of range" (I'm using Java 8, of course), when it should be in range (the value assigned is precisely 264−1):
public class Foo {
static long values = 18446744073709551615L;
public static void main(String[] args){
System.out.println(values);
}
}
So, is there any way to declare an unsigned int or long?
Well, even in Java 8, long
and int
are still signed, only some methods treat them as if they were unsigned. If you want to write unsigned long
literal like that, you can do
static long values = Long.parseUnsignedLong("18446744073709551615");
public static void main(String[] args) {
System.out.println(values); // -1
System.out.println(Long.toUnsignedString(values)); // 18446744073709551615
}