Friday, May 30, 2008

How to properly print a hexadecimal byte array in Java

Here is a JUnit snippet of how to properly print a hexadecimal byte array in Java. The byte array may actually be an array of integers as well.


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

public class HeksTest {

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

int[] parameterArray = new int[5];
parameterArray[0] = bs[0];
parameterArray[1] = bs[1];
parameterArray[2] = bs[2];
parameterArray[3] = bs[3];
parameterArray[4] = bs[4];


StringBuffer sb = new StringBuffer();
String hexString = "";
for (int i = 0; i < 5; i++) {
hexString = Integer.toHexString(0xFF & parameterArray[i]).toUpperCase();
if (hexString.length() == 1) {
// i.e. if its "4" then print out as "04"
sb.append("0");
}
sb.append(hexString);
sb.append(" ");
}

int length = sb.length();
sb.setLength(length - 1);
hexString = sb.toString();

System.out.println("address (hex) = [" + hexString + "]");

assertTrue("CA 00 00 16 04".equals(hexString));

hexString = null;
}

}


Perhaps the most important line in the above code is the one shown below. Take note of the toHexString method used here. Also, the array element conversion uses 0xFF to ensure that negative values are converted properly.


hexString = Integer.toHexString(0xFF & parameterArray[i]).toUpperCase();