我正在尝试创建一个"CheckSum 8 Xor“
到目前为止,这是我的代码
String check = "00 02 01 03 c0 30 30 31 e1 c7 90 1c 44 54 61 6e 79 61 20 20 20 20 20 20 20 20 20 20 20 1c 44 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 04";
int getCheckSum(String check)
{
byte[] chars = check.getBytes();
int XOR = 0;
for (int i = 0; i < check.length(); i++)
{
XOR ^= Integer.parseInt(toHexString(chars[i]));
}
return XOR;
}但是返回的值是"18“,而应该是"20”。
输入是我在这里检查的十六进制,它可以正确计算
http://www.scadacore.com/field-applications/programming-calculators/online-checksum-calculator/
发布于 2018-09-27 18:37:22
你必须用空格分割你的输入字符串:
public static int getCheckSum(String str) {
int xor = 0;
String[] arr = str.split(" ");
for (int i = 0; i < arr.length; i++)
xor ^= Integer.parseInt(arr[i], 16);
return xor;
}或者使用streams:
public static int getCheckSum(String str) {
return Arrays.stream(str.split(" "))
.map(s -> Integer.parseInt(s, 16))
.reduce((a, b) -> a ^ b)
.orElse(0);
}https://stackoverflow.com/questions/38727547
复制相似问题