Search code examples
javaphppack

Need Java equivalent to pack("H32", param) from php


I need a java equilavent from this php code:

$string = "testing";
$hexchal = pack('H32', $string);

I did search the internet, but found no answer.

Thanks in advance!


Solution

  • I don't think your code above works. You expect the string to be in Hex format. This should do the trick, but not as nice as php.

    String hex = "4a616d6573";
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < hex.length(); i+=2) {
        String str = hex.substring(i, i+2);
        output.append((char)Integer.parseInt(str, 16));
    }
    System.out.println(output);