[英]Need help converting perlscript to java
i need to convert this perlscript to java.我需要将此 perlscript 转换为 java。 But i can not read perl.
但我无法阅读 perl。 Can somebdoy help me plz.
有人可以帮助我吗?
sub checksum16 ($) {
my @bytes = unpack("C*", $_[0]);
my $sum = 0;
foreach(@bytes) {
$sum += $_;
$sum %= 2**16;
}
return $sum;
}
What is $_ and $_[0]? $_ 和 $_[0] 是什么? Its not defined and what is unpack("C*", ... for?
它没有定义,什么是 unpack("C*", ... for?
The "C*" means unsigned char (octet value), see perldoc pack , so you could try something like this: “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;
}
}
Update :更新:
Java does not seem to have an unsigned byte
type, so you can use int
to hold the bytes instead: 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.