1

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

I got an MD5 String

de70d4de8c47385536c8e08348032c3b

and I need it as the Byte Values

DE 70 D4 DE 8C 47 38 55 36 C8 E0 83 48 03 2C 3B

This should be similar to Perls pack("H32); function.

Community
  • 1
  • 1
Moritz
  • 153
  • 1
  • 9

4 Answers4

3

you may take a look at Apache Commons Codec Hex.decodeHex()

Alex Stybaev
  • 4,623
  • 3
  • 30
  • 44
2

Loop over the String and use Byte.decode(String) function to fill a byte array.

Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
1

unverified:

String md5 = "de70d4de8c47385536c8e08348032c3b";
byte[] bArray = new byte[md5.length() / 2];
for(int i = 0, k = 0; i < md5.lenth(); i += 2, k++) {
    bArray[k] = (byte) Integer.parseInt(md5[i] + md5[i+1], 16);
}
juergen d
  • 201,996
  • 37
  • 293
  • 362
1

There are many ways to do this. Here is one:

public static void main(String[] args) {

    String s = "de70d4de8c47385536c8e08348032c3b";

    Matcher m = Pattern.compile("..").matcher(s);

    List<Byte> bytes = new ArrayList<Byte>();
    while (m.find())
        bytes.add((byte) Integer.parseInt(m.group(), 16));

    System.out.println(bytes);
}

Outputs (-34 == 0xde):

[-34, 112, -44, -34, -116, 71, 56, 85, 54, -56, -32, -125, 72, 3, 44, 59]
dacwe
  • 43,066
  • 12
  • 116
  • 140