Perl's pack function equivalent in Java

那年仲夏 提交于 2019-12-20 03:34:07

问题


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;

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/10101332/perls-pack-function-equivalent-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!