freddy888
freddy888

Reputation: 1010

python calculate signed crc32 integer to checksum

I have the following string I would like to calculate a checksum for.

3556.5:200:3557.0:2:3556.4:84:3557.4:4:3555.7:6:3557.7:14:3555.1:46:3558.6:21:3552.9:14:3558.7:10:3552.8:194:3558.8:106:3552.7:10:3558.9:10:3552.6:25:3560.2:178:3552.5:4:3560.5:111:3551.7:1:3561.7:1:3551.6:65:3562.5:18:3551.0:103:3562.6:111:3550.7:3:3562.7:3:3550.6:4:3562.8:185:3550.5:1:3563.7:1:3550.3:84:3564.2:1:3550.2:156:3564.8:153:3550.0:82:3565.0:400:3549.7:1:3565.9:60:3548.4:104:3566.1:20:3547.2:177:3566.5:40:3545.9:1:3568.0:20:3545.1:11:3569.4:12:3545.0:71:3570.0:82:3544.9:1:3570.6:4

I do it the following

string2 = string.encode('ascii')
checksum = zlib.crc32((string2))

This gives me an integer of 3467096777. However, the server provider says it should be -949017128. Additionally, I tried many variants of the string and always ended up with a positive number, which somehow leads me to the possibility that my way of calculating a signed crc32 integer is wrong.

I converted the -949017128 via the following

checksum_server = -949017128 & 0xffffffff

it yields 3345950168, which is still different from mine.

Is there a way to calculate the string out of the signed crc32 integer -949017128?

Upvotes: 1

Views: 1754

Answers (1)

Yundong Cai
Yundong Cai

Reputation: 79

I think it is the BTC's price at okex. What a good time!

crc32 of zlib returns a unsigned number which is different from signed number as the API documentation; if the server check_sum is positive, they should be equal; if server check_sum is negative, there is a need to check as below (should have better solution):

check_sum = zlib.crc32(checksum_str.encode("utf-8"))
if server_check_sum < 0 and 2 ** 32 - check_sum + server_check_sum == 0 or server_check_sum == check_sum:
    print(f"{instrument_id}: checksum successful")

You must ensure the string is corrected formatted, no "0" added if you do the type conversion.

Upvotes: 1

Related Questions