Convert a byte array to integer in Java and vice versa

Convert a byte array to integer in Java and vice versa

To convert a byte array to an integer and vice versa in Java, you can use the ByteBuffer class from the java.nio package. Here's how you can do it:

Convert a Byte Array to an Integer:

import java.nio.ByteBuffer; public class ByteArrayToInteger { public static void main(String[] args) { byte[] byteArray = {0, 0, 0, 42}; // Example byte array representing an integer value // Convert the byte array to an integer int intValue = ByteBuffer.wrap(byteArray).getInt(); System.out.println("Integer value: " + intValue); } } 

In this code, we use ByteBuffer.wrap(byteArray).getInt() to convert the byte array byteArray into an integer value.

Convert an Integer to a Byte Array:

import java.nio.ByteBuffer; public class IntegerToByteArray { public static void main(String[] args) { int intValue = 42; // Example integer value // Convert the integer to a byte array byte[] byteArray = ByteBuffer.allocate(4).putInt(intValue).array(); for (byte b : byteArray) { System.out.print(b + " "); } } } 

In this code, we use ByteBuffer.allocate(4).putInt(intValue).array() to convert the integer intValue into a byte array. The allocate(4) method specifies the size of the byte array (4 bytes for an integer).

Using ByteBuffer is a convenient and reliable way to perform these conversions because it handles endianness (byte order) and provides a consistent way to work with binary data in Java.


More Tags

python-c-api gantt-chart root array-broadcasting virtualscroll uint alphanumeric abap tablespace httpcontent

More Java Questions

More Organic chemistry Calculators

More Financial Calculators

More Weather Calculators

More Genetics Calculators