I have a sequence of byte arrays of size 8 (64 bits). I want to put the corresponding natural number into a variable (of primitive type), for this reason i thought to use a double variable because the other primitive types do not support a so high range (from 0 to 2^64).
I show an example:
I have the following array of bytes
000000 0000000 0000000 0000000 0000000 0000000 0000000 0000010
the corresponding natural number is 2.
I have tried this:
double bigNaturalNum = new BigInteger(byteArray).doubleValue();
There problem is that the doubleValue() method returns the double value that the byte represents, thus the resulting value can be a decimal value.
2 Answers 2
This depends if the most significant bit in the byte[] is used as the sign bit e.g. two's complement. If so you can map byte[] to long with ByteBuffer:
byte[] arr = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff };
long l = ByteBuffer.wrap(arr).getLong();
System.out.println(l); // -1
System.out.println(Long.toHexString(l)); // ffffffffffffffff
If not you should use BigInteger with signum=1 to indicate that you don't use sign bit:
byte[] arr = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff };
BigInteger i = new BigInteger(1, arr);
System.out.println(i); // 18446744073709551615
Comments
I have finally solved storing the value in a long variable. Java has not an unsigned long primitive type but from JavaSE 8, you can treat the long variable as an unsigned long variable through the methods of class Long Long - JavaSE 8.
You can use for instance the method public static int compareUnsigned(long x, long y) which
Compares two long values numerically treating the values as unsigned.
In this way you can store 2^64 natural nubers in a long variable.
long(64-bit integer), rather thandouble(double-precision floating-point)?BigIntegeris for. Do you want anlongfor when the number is within the range oflong, and adoublefor when it exceeds the range?longis 64-bit signed. There are no suitable unsigned primitives in Java (only the weird 16-bitchar). So you need an object, or treatlongas if it were unsigned knowing that it is signed.