Sunday 7 November 2021

Java: Convert byte array to an integer

In this post, I am going to explain how to convert byte array to an integer. While converting the byte array to integer, we should consider the byte order also.

 

There are two standard byte array order formats.

a.   BIG_ENDIAN: In this order, the bytes of a multibyte value are ordered from most significant to least significant.

b.   LITTLE_ENDIAN: In this order, the bytes of a multibyte value are ordered from least significant to most significant.

 

For example, below snippet convert the byte array in BIG_ENDIAN format to an integer.

 

int intInBigEndian = ByteBuffer.wrap(byteArr1).order(ByteOrder.BIG_ENDIAN).getInt();

 

ByteArrayToInteger.java

package com.sample.app.numbers;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class ByteArrayToInteger {

	public static void main(String args[]) {
		byte[] byteArr1 = { 0, -68, 97, 78 };

		int intVal = ByteBuffer.wrap(byteArr1).order(ByteOrder.BIG_ENDIAN).getInt();

		System.out.println("intVal -> " + intVal);
	}

}

 

Output

intVal -> 12345678

 

 

 

You may like

No comments:

Post a Comment