Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckSum 8 Xor wrong result

Tags:

java

checksum

xor

I am trying to create a "CheckSum 8 Xor"

this is my code so far

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

but the value returned is "18" When it is suppose to be "20"

The input is HEX i checked here and it calculates correctly

http://www.scadacore.com/field-applications/programming-calculators/online-checksum-calculator/

like image 867
Tanya Visagie Avatar asked Oct 21 '25 08:10

Tanya Visagie


1 Answers

You have to split your input string with spaces:

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

Or using 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);
}
like image 156
oleg.cherednik Avatar answered Oct 23 '25 22:10

oleg.cherednik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!