Convert Byte Array to Integer in Java

Byte comes under the primitive data types in Java. A byte array in Java is an array containing bytes and stores a collection of binary data. The integer data type represents integers in Java. Bytes and integers are closely linked because binary data can be converted to integer form.
In this article, we will convert a byte array to an integer type in Java.
The ByteBuffer
class present in the java.nio
package in Java provides us with a method to convert the byte array into an integer.
See the code below.
import java.nio.ByteBuffer;
public class Test {
public static void main(String[] args) {
byte [] bytes = { 0x00,0x01,0x03,0x10 };
System.out.println(ByteBuffer.wrap(bytes).getInt()+" ");
}
}
Output:
66320
In the above code, we created a Bytebuffer
of a given length of the byte array, and after that, we read the next four bytes from it as an integer type. The ByteBuffer
method wraps the byte array into a buffer, and the getInt()
function reads the next four bytes in the class as an integer.
Below we have another example of ByteBuffer
class. In the code below, we allocate the memory by two only. The function performed by the methods is the same as the previous one. Here it converts each byte separately as we can see it gives two different outputs.
See the code below.
import java.nio.*;
class Byte_Array_To_Int {
static void byte_To_Int(byte ar[]) {
ByteBuffer wrapped = ByteBuffer.wrap(ar); // big-endian by default
short num = wrapped.getShort();
ByteBuffer dbuf = ByteBuffer.allocate(2);//allocates the memory by 2.
dbuf.putShort(num);
byte[] bytes = dbuf.array();
for(int i=0;i< bytes.length;i++) {// loop for printing the elements.
System.out.println(bytes[i]);
}
}
public static void main(String[] args){
byte[] b = {0x03, 0x04};// byte type array.
byte_To_Int(b);
}
Output:
3
4
The ByteBuffer.wrap()
wraps the array into a buffer. By default, it stores the data in the form of the big-endian 0x00 type. Notice that in the output, we have two different integers. As discussed earlier, this code takes each element present in the array and converts it accordingly.
Related Article - Java Array
- Concatenate Two Arrays in Java
- Convert Byte Array in Hex String in Java
- Remove Duplicates From Array in Java
- Count Repeated Elements in an Array in Java
- Natural Ordering in Java
- Slice an Array in Java