简体   繁体   English

Java十进制/ ASCII和基数转换

[英]Java decimal/ascii and base converting

I'm converting code from perl to java. 我正在将代码从Perl转换为Java。 I'm sort of stuck on finding the equivalents in java. 我有点想在Java中找到等效项。

Here's my Perl code: 这是我的Perl代码:

    for($i = 0; $i < strlen($hex_); $i = $i + 2)
    {
      $ascii = $ascii.chr(hexdec(substr($hex_, $i, 2))); 
    }

so in java i can do hex.substring(i,2). 所以在Java中我可以做hex.substring(i,2)。 I got that part. 我有那部分。

How would I do the chr and hexdec part in Java? 我将如何在Java中使用chr和hexdec?

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) . 无需手动解析十六进制数,只需使用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. 类似地,有一个Integer.toString(int i,int radix)可以将您的整数转换为具有所需基数的String。

I'm actually extremely surprised you didn't use pack for your Perl version! 我真的很惊讶您没有为您的Perl版本使用pack

$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: 无论如何,如果要手动编码(而不是像Apache Commons Codec这样的东西),Perl代码的Java端口是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM