user2914191 user2914191 - 1 year ago 218
MySQL Question

Java CRC32 does not match MySQL CRC32

I need Java's CRC32 to match MySQL's CRC32, but I'm getting different results.


MariaDB> SELECT CRC32(148595460);
| CRC32(148595460) |
| 4137475682 |
1 row in set (0.00 sec)


Checksum checksum = new CRC32();
checksum.update(ByteBuffer.allocate(4).putInt(148595460).array(), 0, 4);
System.out.println("Checksum: " + checksum.getValue());

Checksum: 747753823

Why does this happen? I'm guessing MySQL interprets the number as a string?

Answer Source

I believe your observations can be explained by a close look at the APIs for MariaDB and Java:


Computes a cyclic redundancy check value and returns a 32-bit unsigned value. The result is NULL if the argument is NULL. The argument is expected to be a string and (if possible) is treated as one if it is not.

In other words, when you call CRC32(148595460) in MariaDB it is using the string 148595460. Now let's look at Java.


From the documentation for CRC32.update:

Updates the CRC-32 checksum with the specified array of bytes.

In other words, you passed in the int value 148595460 which then was converted to a byte array.

If you try the following Java code I believe you will get the behavior you want:

Checksum checksum = new CRC32();
byte[] b = "148595460".getBytes();
system.out.println("Checksum: " + checksum.getValue());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download