Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a byte array to its numeric value (Java)?

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.

like image 264
pirate Avatar asked Jun 22 '09 11:06

pirate


People also ask

How do you convert bytes to numbers?

To convert bytes to int in Python, use the int. from_bytes() method. A byte value can be interchanged to an int value using the int. from_bytes() function.

Can we convert byte to int in Java?

The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.

Can we convert byte array to file in Java?

In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.


2 Answers

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 
like image 78
coobird Avatar answered Oct 08 '22 07:10

coobird


Assuming the first byte is the least significant byte:

long value = 0; for (int i = 0; i < by.length; i++) {    value += ((long) by[i] & 0xffL) << (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.

like image 21
Mnementh Avatar answered Oct 08 '22 07:10

Mnementh