I am looking for one datatype with exact capacity of 0 to 2^64 - 1. We know that Java as it is does not support 'unsigned' barring char datatype.
There is BigInteger class that allows creation of larger numbers that long datatype cannot support. But I am not sure how BigInteger class would serve my purpose. BigInteger class allows assignment through constructors only. I see the following possibility but it generates a random number.
BigInteger(int numBits, Random rnd)
Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2^numBits - 1), inclusive.
I can't see any setValue(x) kind of API that'd let me choose my own value to this BigInteger. How to implement this using BigInteger class or is there any other way of doing it? Please post code sample.
PS: The question posted by someone here does not have implementation details.
In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2^64-1.
To input a uint64 into a BigInteger
, you can use a constructor that takes a byte array and a signum:
public static BigInteger bigIntegerFromUInt64(long uint64) {
if (uint64 < 0) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(uint64);
byte[] uint64Bytes = buffer.array();
return new BigInteger(/* signum */ 1, uint64Bytes);
} else {
return BigInteger.valueOf(uint64);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With