Friday, May 30, 2008

Convert byte array to integer in Java

The following JUnit test shows how to convert a byte array into a single integer in Java.


import static org.junit.Assert.*;
import org.junit.Test;

public class BaitTest {

@Test
public void printInt() {
byte[] bs = {
(byte)0x00,
(byte)0x00,
(byte)0x00,
(byte)0x16,
(byte)0x04
};

int address = (bs[0] << 32) | (bs[1] << 24) |
(bs[2] << 16) | (bs[3] << 8) | bs[4];

System.out.println("address (int) = [" + address + "]");
System.out.printf("address (hex) = [%X]\n", address);

assertTrue(5636 == address);
}
}


In the above, the line :

int address = (bs[0] << 32) | (bs[1] << 24) |
(bs[2] << 16) | (bs[3] << 8) | bs[4];

is where we convert the byte array to a single integer using the assumption that the most significant byte (i.e. MSB) is at index 0. Note that the bit shift values are incremented by multiples of 8 i.e. or 8*0, 8*1, 8*2, 8*3 and 8*4.

In Java 5 upwards, to print a decimal number as hexadecimal, use the "%X" modifier in "printf", as shown in this line from the above code :

System.out.printf("address (hex) = [%X]\n", address);


You'll see that the above will print out "1604" (i.e. 00 00 00 16 04) which is what the byte array looks like at the top of the code, i.e. :


byte[] bs = {
(byte)0x00,
(byte)0x00,
(byte)0x00,
(byte)0x16,
(byte)0x04
};