I am trying to implement a Cyclic Redundancy Check with Java and I made a quick code to see if it works as intended.
I have to take a large amount of data (128 bytes) and check it with CRC, so I figured I should store the binary value in a BigInteger to perform the calculations. I thought about using a byte array, but I am not sure how I would perform a mod on a byte array.
To test the code, I used small values, but I got an unexpected result for my remainder values.
// Set G value
BigInteger bigI = new BigInteger("110010", 2);
String str = bigI.toString(2);
System.out.println("G = " + str);
System.out.println(bigI);
// Set D value
BigInteger bigI2 = new BigInteger("1011010010", 2);
String str2 = bigI2.toString(2);
System.out.println("D1 = " + str2);
// Append zeroes to D
String str3 = str2 + "00000";
bigI2 = new BigInteger(str3, 2);
str3 = bigI2.toString(2);
System.out.println("D2 = " + str3);
System.out.println(bigI2);
// Get R value
BigInteger bigI3 = bigI2.mod(bigI);
String str4 = bigI3.toString(2);
System.out.println("R = " + str4);
// Add R to D
BigInteger bigI4 = bigI3.add(bigI2);
String str5 = bigI4.toString(2);
System.out.println("D3 = " + str5);
// Get final remainder (nonzero == error)
BigInteger bigI5 = bigI4.mod(bigI);
String str6 = bigI5.toString(2);
System.out.println("Remainder = " + str6);
My output is:
G = 110010
50
D1 = 1011010010
D2 = 101101001000000
23104
R = 100
D3 = 101101001000100
Remainder = 1000
When I mod the first two values (23104 and 50) I get 4. I double checked that on my calculator and it was the same (using decimal). However, if you take the binary values (110010 and 101101001000000) and mod them you should get 1000 (in binary), but 0b1000 != 4.
I watched this video on YouTube and I used the same values but I am getting the different result.
Am I using BigInteger incorrectly?
The calculation of a CRC is getting the remainder (modulo) of dividing a binary polynomial by another binary polynomial. It has nothing whatsoever to do with integer division.