How to convert hex strings to byte values in Java

I have a String array. I want to convert it to byte array. I use the Java program. For example:

String str[] = {"aa", "55"};

convert to:

byte new[] = {(byte)0xaa, (byte)0x55};

What can I do?


Solution 1:

String str = "Your string";

byte[] array = str.getBytes();

Solution 2:

Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?

If yes, then for each string item I would do the following:

  1. check that a string consists only of 2 characters
  2. these chars are in '0'..'9' or 'a'..'f' interval (take their case into account as well)
  3. convert each character to a corresponding number, subtracting code value of '0' or 'a'
  4. build a byte value, where first char is higher bits and second char is lower ones. E.g.

    int byteVal = (firstCharNumber << 4) | secondCharNumber;