How to Convert Byte Array to Integer In Java?

Convert Byte Array to Integer In Java

Do you want to know how to convert a byte array to an integer in Java 🤔?

The fundamental unit of information in computer storage and processing is the byte. A practical method for managing several bytes simultaneously is to use the primitive types offered in the Java programming language. As a result, a byte array and primitive types have an intrinsic connection to conversion.

In this article, we’ll discuss different approaches to converting a byte array to an integer in Java.  So without further ado, let’s dive deep into the topic and see some real examples. 

 

 

What is a Byte Array in Java?

As we’ve discussed in Java, bytes are classified as basic data types. A Java byte array is a collection of binary data that is stored as an array of bytes. In Java, integers are represented by the data type. Due to the fact that binary data may be transformed into an integer, bytes and integers are closely related.

Let’s see an example of a Byte Array in java.

 

Code

public class B_A

{

public static void main(String args[])

{

byte B[];

B = new byte[4];

//ASSIGNING ELEMENTS TO JAVA BYTE ARRAY

B[0] = 80;

B[1] = 10;

B[2] = 2;

B[3] = 9;

System.out.println("Byte Array in java  ");

for(int i=0;i<B.length;i++)

{

System.out.println("Element at Index : "+ i + " is " + B[i]);

}

}

}

}

 

Output

Byte Array in java  

Element at Index : 0 is 80

Element at Index : 1 is 10

Element at Index : 2 is 2

Element at Index : 3 is 9

 

 

How to Convert a Byte Array to Integer in Java?

In Java, there are three solutions to  Convert Byte Array to Integer, they are following; 

  1. Use ByteBuffer class 
  2. Converts each byte separately
  3. Iterate through the array and shifting values

 

 

Method 1: Use ByteBuffer Class

Using the java.nio.ByteBuffer class, you can easily convert a byte array into a numeric number (int).

 

Code

import java.nio.ByteBuffer;

public class ByteArrayInt{

    public static void main(String[] args) {
      
        byte [] Byte_array = { 0x01,0x03,0x11,0x10 };

        System.out.println("Byte _Array to integer: "+ ByteBuffer.wrap(Byte_array).getInt()+" ");
    }
}

 

Output

Byte _Array to integer:16978192

 

In the code above, we first built a byte buffer of the specified size from the byte array, and then we read the next four bytes as an integer type from it. The following four bytes in the class are read as an integer by the getInt() function after the byte array has been wrapped in a buffer by the ByteBuffer method.

It’s important to note that the byte array should contain at least 4 bytes in order to be converted to an integer. If the array is shorter than 4 bytes, you’ll need to pad it with zeros or use a different method to handle the conversion.

Additionally, you can use the ByteBuffer class to convert an integer to a byte array. Here’s how you can do it:

 

Code

ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(num);
byte[] bytes = buffer.array();

 

This code creates a ByteBuffer object with a size of 4 bytes, puts the integer value into the buffer using the putInt method, and then retrieves the resulting byte array using the array method.

You can also use the ByteBuffer class to convert an integer to a byte array in a little-endian or big-endian format, depending on your needs. For example, to convert an integer to a little-endian byte array, you can use the following code:

 

Code

ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(num);
byte[] bytes = buffer.array();

 

This code creates a ByteBuffer object with a size of 4 bytes, sets the byte order to little-endian using the order method, and then puts the integer value into the buffer using the putInt method. The resulting byte array is retrieved using the array method.

 

 

Method 2: Converts Each Byte Separately

We can also convert each byte separately by using the ByteBuffer wrap() function.  Let’s see an example:

 

Code

import java.nio.*;

class ByteArrayInt {

    static void Byte_To_Int(byte array[]) {       

        ByteBuffer wrapped = ByteBuffer.wrap(array);

        short num = wrapped.getShort();     

        ByteBuffer  buffer = ByteBuffer.allocate(3);

        buffer.putShort(num);


        byte[] Bytes = buffer.array(); 
      
        for(int i=0;i< Bytes.length;i++) {

            System.out.println(" Byte converted to Integers are : "+Bytes[i]);
      }
}


public static void main(String[] args){

    byte[] b = {0x01, 0x03 , 0x02};

    Byte_To_Int(b);
}

}

 

Output

Byte converted to Integers are: 1

Byte converted to Integers are: 3

Byte converted to Integers are: 0

 

Only three bits of memory are allotted in the code above. The methods’ function is the same as the preceding one. As we can see, it converts each byte individually in this case and produces two distinct outputs.

The array is wrapped into a buffer via ByteBuffer.wrap(). It saves the information by default as a  0x00 type. You’ll see that there are three distinct integers in the output. As was previously said, this code changes each element in the array accordingly.

 

 

Method 3: Iterate through the array and shifting values

To convert a byte array to an integer, you can use the following code snippet:

 

Code

int num = 0;
for (int i = 0; i < 4; i++) {
    num = (num << 8) | (int) bytes[i] & 0xff;
}

 

This code converts a 4-byte array to an integer by iterating through the array and shifting the existing value of num left by 8 bits before ORing it with the current byte. The & 0xff operation is used to ensure that the resulting integer is unsigned, as Java does not have an unsigned integer type.

 

Conclusion

To summarize the article, we have discussed what a byte array is in Java and how to convert a byte array to an integer in Java. Furthermore, we’ve discussed the three approaches for converting a covert byte array to an integer, and they are the following:

  1. Use ByteBuffer class 
  2. Converts each byte separately
  3. Iterate through the array and shifting values

Let’s have a quick recap of the topics discussed in this article.

  1. What is a Byte Array in Java?
  2. How to convert byte array to integer in Java?
  3. Use ByteBuffer class 
  4. Converts each byte separately

If you’ve found this article helpful, don’t forget to share and comment below, 👇, which solutions have helped you solve the problem.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts
Total
0
Share