1

Possible Duplicate:
Convert a string representation of a hex dump to a byte array using Java?

I am trying to convert a hex string "FFFFFFFFFFFFFFFF" into byte array with size 8

the result should be

byte[] mKey =  { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
        (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };

I have tried the for loop

public static byte[] HexString2Bytes(String src) {
    byte[] res = new byte[8];
    for (int i = 0; i < 16; i = i + 2) {
        res[i] = convertToByte(src.substring(i, i + 2));
    }
    return res;
}

the problem is, I don't know how to implement the method convertToByte() to convert a hex string, like "FF" to 0xFF, please help, thanks.

Community
  • 1
  • 1
Arst
  • 3,098
  • 1
  • 35
  • 42

1 Answers1

0
int convertToByte(String s){
    return Integer.parseString(s, 16);
}
Guy Adini
  • 5,188
  • 5
  • 32
  • 34