2

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?

2
  • In what form do you have those hex codes, String? Commented Mar 8, 2012 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 Commented Mar 8, 2012 at 10:45

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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;
}

prints

0c33b2cfca154c3a3362acfbde34782af31afb606f6806313cc0df40928662edd3ef1d630ab1b75639154d71ed490a36e5f51f6c9d270c4062e8266ad1608bdc496a70f6696fa6e7cd7078c6674188e8a49ecba71fad049a3d483ccac45d27aedfbb31d82adb8135238b858143492b1cbda2e854e735909256365a270095fc

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.