【问题标题】:Need help converting perlscript to java [closed]需要帮助将 perlscript 转换为 java [关闭]
【发布时间】:2022-01-05 13:10:05
【问题描述】:

我需要将此 perlscript 转换为 java。但是我看不懂perl。请问有人能帮帮我吗?

sub checksum16 ($) {
    my @bytes = unpack("C*", $_[0]);
    my $sum = 0;
    foreach(@bytes) {
        $sum += $_;
        $sum %= 2**16;
    }
    return $sum;
}

什么是 $_ 和 $_[0] ?它没有定义,什么是 unpack("C*", ... for?

【问题讨论】:

  • 该函数使用一个16位的计数器,将一些数据的字节值相加。
  • 谢谢:它通过一个字节数组循环。但是要总结什么呢? $sum += $_ $_ 是干什么用的?
  • 它将数组中包含的字节值相加。我不是 Perl 专家,但很容易猜出代码的作用。
  • 快速搜索得到this page 关于Perl foreach 构造的信息。
  • 如果你运行perldoc perlvar,它解释了所有 Perl 的特殊变量。 $_ 是 Perl 的隐式变量,因此通常填充“当前正在处理的事物”,因此在这种情况下是来自 @bytes 在 foreach 循环的这次迭代中的值。

标签: java perl


【解决方案1】:

“C*”表示无符号字符(八位字节值),请参阅perldoc pack,因此您可以尝试以下操作:

public class Checksum
{
    public static void main(String [] args) throws Exception
    {
        String raw = new String(new byte[] {(byte) 0x40, (byte) 0x41});
        byte[] byteArrray = raw.getBytes();
        System.out.println("Result: " + checksum(byteArrray));
    }

    public static int checksum(byte[] arr) {
        int sum = 0;
        for (byte x : arr) {
            sum += x;
            sum %= 65536;
        }
        return sum;
    }
}

更新

Java 似乎没有 unsigned byte 类型,因此您可以使用 int 来保存字节:

public class Checksum
{
    public static void main(String [] args)
    {
        //use int instead of byte since byte is not unsigned
        int[] data = new int[] {0xff, 0x1};
        System.out.println("Result: " + checksum(data));
    }
    
     // assume input array "arr" is unsigned bytes
    public static int checksum(int[] arr) {
        int sum = 0;
        for (int x : arr) {
            // we assume input is unsigned bytes so we should not need to mask
            //  with 0xFF here
            int unsigned_byte = x & 0xFF;
            sum += unsigned_byte;
            sum %= 65536;
        }
        return sum;
    }
}

【讨论】:

    猜你喜欢
    • 2011-07-09
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    相关资源
    最近更新 更多