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.

5
  • 1
    So you want to transform the string from this: de70d4de8c47385536c8e08348032c3b to this: DE 70 D4 DE 8C 47 38 55 36 C8 E0 83 48 03 2C 3B? Commented May 28, 2012 at 13:55
  • Nearly, I don't want this to be seen as the String in a textfile, but as the bytes. Commented May 28, 2012 at 13:56
  • Can you write a unit test? I've no idea which data types you mean. Commented May 28, 2012 at 13:56
  • @npinti looks like he needs that Commented May 28, 2012 at 13:56
  • (Lots of "how do I parse hex in Java" questions - I chose one example.) Commented May 28, 2012 at 13:57

4 Answers 4

3

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

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

Comments

2

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

2 Comments

For example "de" is not parseable by Byte.decode so I don't think it would work.
You need to put "0x" as a prefix.
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]

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.