Home » Programming Languages » Byte Array To Integer And Integer to Byte Array Conversion using JAVA

Byte Array To Integer And Integer to Byte Array Conversion using JAVA

If you are working in some network related data transfer like sending some commands over socket, then its high likely that you will need to convert your integer command number to byte array before sending over socket since data sent over socket is only byte arrays.

Following program briefs above how you can convert Byte Array to Integer (which is normally required at receiver side) and Integer to Byte Array (which is required at sender side)

Integer to Byte Array

private static byte[] intToByteArray(int value) {
    ByteBuffer converter = ByteBuffer.allocate(4);
    converter.putInt(value);
    return converter.array();
}

Byte Array to Integer

        public static int byteArrayToInt(byte[] valueBuf, int offset) {
                ByteBuffer converter = ByteBuffer.wrap(valueBuf);
                return converter.getInt(offset);
        }

Following complete program tries to convert integer “12345” to Byte Array and print as Hex and then convert same ByteArray to Integer to verify that both conversion works fine.

$ vim ByteArrayAndIntConv.java
import java.io.*;
import java.nio.ByteBuffer;

public class ByteArrayAndIntConv {
        private static String printHex = null;

        private static byte[] intToByteArray(int value) {
                ByteBuffer converter = ByteBuffer.allocate(4);
                converter.putInt(value);
                return converter.array();
        }

        public static int byteArrayToInt(byte[] valueBuf, int offset) {
                ByteBuffer converter = ByteBuffer.wrap(valueBuf);
                return converter.getInt(offset);
        }

        public static void main(String[] args) throws Exception {
                byte exampleByteArray[] = null;
                final Integer integer = 12345;
                exampleByteArray = intToByteArray(integer);
                for (int i=0; i<4; i++) {
                        printHex = String.format("%02X", exampleByteArray[i]);
                        System.out.println(printHex);
                }

                byte[] byteArray = {0x00, 0x00, 0x30, 0x39};
                int exampleInt = byteArrayToInt(byteArray, 0);
                System.out.println("Integer Converted from ByteArray: " + exampleInt);

        }
}

Now, we will compile and execute the program as below,

$ javac ByteArrayAndIntConv.java
$ java ByteArrayAndIntConv

00
00
30
39
Integer Converted from ByteArray: 12345

As we can see above, 0x00003039 is an hex value of Integer 12345

Reference : Android CTS Code


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment