Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 校验和8异或错误结果_Java_Checksum_Xor - Fatal编程技术网

Java 校验和8异或错误结果

Java 校验和8异或错误结果,java,checksum,xor,Java,Checksum,Xor,我正在尝试创建一个“校验和8异或” 这是到目前为止我的代码 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

我正在尝试创建一个“校验和8异或”

这是到目前为止我的代码

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;
}
String check=“00 02 01 03 c0 30 31 e1 c7 90 1c 44 54 61 6e 79 61 20 20 20 20 20 20 20 20 20 20 04”;
int getCheckSum(字符串检查)
{
byte[]chars=check.getBytes();
int-XOR=0;
对于(int i=0;i
但如果假定返回值为“20”,则返回值为“18”

输入是十六进制,我在这里检查,它计算正确


您必须用空格分隔输入字符串:

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;
}

因为它没有特定于Android的代码,所以应该使用Java标记。而且,正如您所知,
“00 02”。getBytes()
可能不会像您认为的那样返回
{00,02}
。正如@cricket\u 007所述,您没有正确地将数据转换为字符。如果要使用十六进制,则应使用字符数组并跳过转换。可能需要尝试
检查.split(“”
整型.valueOf(字符串s,整数基数)
。看见
public static int getCheckSum(String str) {
    return Arrays.stream(str.split(" "))
                 .map(s -> Integer.parseInt(s, 16))
                 .reduce((a, b) -> a ^ b)
                 .orElse(0);
}