Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned CRC 32 for Python to match Java's CRC 32?

A Python client communicates with a Java server across an unreliable channel, and they must communicate package corruption via CRC32.

On Java's end, the CRC 32 is unsigned:

//where data is a byte[]
crc.update(data, 8, data.length-8);
long chksum = crc.getValue();

But on Python's end, the CRC 32 is signed:

//where some_segment is a bytearray() of data
crc = zlib.crc32(some_segment)

Is there a way to compute the checksum in Python's crc32 to match that of Java's? In other words, make python's crc32 unsigned?

like image 362
Victor Lin Avatar asked Jun 03 '26 17:06

Victor Lin


2 Answers

You can bitwise the result with 0xffffffff to get an unsigned value:

crc = zlib.crc32(some_segment) & 0xffffffff

In Python 3 this is the default, so you only need this on python 2.X, but will work for both versions.

like image 107
AChampion Avatar answered Jun 05 '26 08:06

AChampion


Do & 0xffffffff on the crc.

like image 36
Mark Adler Avatar answered Jun 05 '26 07:06

Mark Adler



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!