2

I have some Perl code that I need to transpose in Java. In this code I have to deal with Perl's pack. Is there an equivalent function in Java? The Perl code looks something like this:

$somevar = pack "H*", $vartopack;
zb226
  • 9,586
  • 6
  • 49
  • 79
artaxerxe
  • 6,281
  • 21
  • 68
  • 106

2 Answers2

2

Perl's pack / unpack functions are a highly versatile conversion utility with its own format syntax (used in H* here, which makes it take an arbitrarily long hex string as input) of which there is no direct equivalent in the Java world. However, to translate...

$somevar = pack "H*", $vartoconvert;

...to Java, you can for example use:

byte[] somevar = javax.xml.bind.DatatypeConverter.parseHexBinary(vartoconvert);

For more information read the DatatypeConverter class reference from Javadocs.

zb226
  • 9,586
  • 6
  • 49
  • 79
artaxerxe
  • 6,281
  • 21
  • 68
  • 106
1
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);
Zhasulan Berdibekov
  • 1,077
  • 3
  • 19
  • 39