Tuesday, June 13, 2023

How to Convert Integer to Byte Array in Java

Converting an Integer to a Byte Array and Vice Versa in Java

In this guide, we will discuss how to convert an integer to a byte array and vice versa in Java. Here is the Java code for doing so:

Code for Converting an Integer to a Byte Array


public byte[] intToByteArray(int value) {
 byte[] byteArray = new byte[4];
 byteArray[0] = (byte)(value >> 24);
 byteArray[1] = (byte)(value >> 16);
 byteArray[2] = (byte)(value >> 8);
 byteArray[3] = (byte)(value);
 return byteArray;
}

Code for Converting a Byte Array to an Integer


public int byteArrayToInt(byte bytes[]) {
 return ((((int)bytes[0] & 0xff) << 24) |
 (((int)bytes[1] & 0xff) << 16) |
 (((int)bytes[2] & 0xff) << 8) |
 (((int)bytes[3] & 0xff)));
}

This code uses the big endian format, which is commonly used in Java. If you're working in C on an x86 system, you'll need to use the little endian format. This requires changing the array index order from 0, 1, 2, 3 to 3, 2, 1, 0. You can modify the code as follows:


byteArray[3] = (byte)(value >> 24);
byteArray[2] = (byte)(value >> 16);
byteArray[1] = (byte)(value >> 8);
byteArray[0] = (byte)(value);

Using the Functions

Here's an example of how to use these functions to convert an integer to a byte array and back again in Java:


int value = 123456789;
byte[] byteArray = intToByteArray(value);
int newValue = byteArrayToInt(byteArray);

I hope this guide has been helpful to you!


0 개의 댓글:

Post a Comment