views:

2628

answers:

3

Hi everyone,

I have an 8 byte array and I want to convert it to its corresponding numeric value.

e.g.

byte[] by = new byte[8];  // the byte array is stored in 'by'

// CONVERSION OPERATION
// return the numeric value

I want a method that will perform the above conversion operation.

+8  A: 

One could use the Buffers that are provided as part of the java.nio package to perform the conversion.

Here, the source byte[] array has a of length 8, which is the size that corresponds with a long value.

First, the byte[] array is wrapped in a ByteBuffer, and then the ByteBuffer.getLong method is called to obtain the long value:

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();

System.out.println(l);

Result

4

I'd like to thank dfa for pointing out the ByteBuffer.getLong method in the comments.


Although it may not be applicable in this situation, the beauty of the Buffers come with looking at an array with multiple values.

For example, if we had a 8 byte array, and we wanted to view it as two int values, we could wrap the byte[] array in an ByteBuffer, which is viewed as a IntBuffer and obtain the values by IntBuffer.get:

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4});
IntBuffer ib = bb.asIntBuffer();
int i0 = ib.get(0);
int i1 = ib.get(1);

System.out.println(i0);
System.out.println(i1);

Result:

1
4
coobird
+1 for array with multiple values
dfa
what about ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4}).getLong()? this method should read next 8 byte and convert them to a long
dfa
@dfa: Thanks for pointing that out, it sure seems to work -- I'll edit the answer. :)
coobird
+4  A: 

Assuming the first byte is the least significant byte:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value += (by[i] & 0xff) << (8 * i);
}

Is the first byte the most significant, then it is a little bit different:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value = (value << 8) + (by[i] & 0xff);
}

Replace long with BigInteger, if you have more than 8 bytes.

Thanks to Aaron Digulla for the correction of my errors.

Mnementh
Aaron Digulla
You are right. I fixed it, hopefully it's now correct.
Mnementh
+3  A: 

If this is an 8-bytes numeric value, you can try:

BigInteger n = new BigInteger(byteArray);

If this is an UTF-8 character buffer, then you can try:

BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));
Vincent Robert
I would've voted for this answer if it ended right after the first code snippet, or if it included some code to convert the string into a "numeric value". As-is, the second half of your answer seems like a non sequitur.
Laurence Gonsalves
Not what I meant in the first place, I changed my answer
Vincent Robert