Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement an unsigned 64-bit int in Java using BigInteger class?

Tags:

java

types

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.

like image 848
Real Red. Avatar asked Apr 20 '09 08:04

Real Red.


2 Answers

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.

like image 52
crownus Avatar answered Oct 16 '22 16:10

crownus


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);
  }
}
like image 25
weston Avatar answered Oct 16 '22 14:10

weston