Take the 2-minute tour ×

I have many hexcodes here and I want to get them into Java without appending 0x to every entity. Like:

0102FFAB and I have to do the following:

byte[] test = {0x01, 0x02, 0xFF, 0xAB};

And I have many hexcodes which are pretty long. Is there any way to make this automatically?

share|improve this question
In what form do you have those hex codes, String? –  Thomas Mar 8 '12 at 10:44
no just plaintext in a file.... but i do not want to read them out of that file, just get them hardcoded into the java program –  vlad Mar 8 '12 at 10:45
add comment

2 Answers

up vote 2 down vote accepted

You could try and put the hex codes into a string and then iterate over the string, similar to this:

String input = "0102FFAB";
byte[] bytes = new byte[input.length() / 2];

for( int i = 0; i < input.length(); i+=2)
  bytes[i/2] = Integer.decode( "0x" + input.substring( i, i + 2 )  ).byteValue();

Note that this requires even length strings and it is quite a quick and dirty solution. However, it should still get you started.

share|improve this answer
it's quick and dirty but it works for that :-) –  vlad Mar 8 '12 at 13:41
add comment

You can use BigInteger to load a long hex string.

public static void main(String[] args) {
    String hex = "c33b2cfca154c3a3362acfbde34782af31afb606f6806313cc0df40928662edd3ef1d630ab1b75639154d71ed490a36e5f51f6c9d270c4062e8266ad1608bdc496a70f6696fa6e7cd7078c6674188e8a49ecba71fad049a3d483ccac45d27aedfbb31d82adb8135238b858143492b1cbda2e854e735909256365a270095fc";
    byte[] bytes2 = hexToBytes(hex);
    for(byte b: bytes2)
        System.out.printf("%02x", b & 0xFF);


public static byte[] hexToBytes(String hex) {
    // add a 10 to the start to avoid sign issues, or an odd number of characters.
    BigInteger bi2 = new BigInteger("10" +hex, 16);
    byte[] bytes2 = bi2.toByteArray();
    byte[] bytes = new byte[bytes2.length-1];
    System.arraycopy(bytes2, 1, bytes, 0, bytes.length);
    return bytes;



note: it handles the possibility that there is one hex value short at the start.

share|improve this answer
add comment

Your Answer


