I'm converting code from perl to java. I'm sort of stuck on finding the equivalents in java.
Here's my Perl code:
for($i = 0; $i < strlen($hex_); $i = $i开发者_如何学JAVA + 2)
{
$ascii = $ascii.chr(hexdec(substr($hex_, $i, 2)));
}
so in java i can do hex.substring(i,2). I got that part.
How would I do the chr and hexdec part in Java?
Here's what I have so far
There is no need for you to go about parsing hexadecimal numbers manually, you can just use Integer.parseInt(String s, int radix). Similarily, there is an Integer.toString(int i, int radix) which will convert your integer to a String with the desired base.
I'm actually extremely surprised you didn't use pack
for your Perl version!
$ascii = pack 'H*', $hex_;
Anyway, the Java port of your Perl code, if you want to code it manually (as opposed to using something like Apache Commons Codec) is:
StringBuilder sb = new StringBuilder();
for (int i = 0; i + 1 < hex.length(); i += 2)
sb.append((char) Integer.parseInt(hex.substring(i, i + 2)));
String ascii = sb.toString();
精彩评论