0
votes

I want to get CRC32 of string which contains binary data. I tried to use somethink like this:

binascii.crc32(binascii.a2b_uu(my_binary_string))

But it often throws exceptions for larger strings. Example content for my binary string:

my_binary_string = "0100101010..."

It can be really long. How can I do this ?

2
you need a hex output right? - Ajay
Hex output is ok, I think I can convert it to whatever I need. - Bouncer00
what is the maximum length of binary data? - Ajay
binascii.crc32(binascii.b2a_hex('10000101010101001')); Out[10]: 945985288 - Ajay
binascii.crc32(binascii.b2a_hex(my_binary_string)) : TypeError: 'str' does not support the buffer interface - Bouncer00

2 Answers

1
votes

Ajay's answer is incorrect as it treats the binary data as a literal string - each 1 or 0 gets encoded into a separate byte.

Assuming your data is binary from UTF-8 encoding or just bytes concatenated into a long string, you should instead do something like this:

import binascii
data = '0110100001100101011011000110110001101111' # 'hello' encoded in UTF-8
int_arr = [int(data[i:i+8], 2) for i in range(0, len(data), 8)] # split the data into 8-bit chunks
print(hex(binascii.crc32(bytes(int_arr))))

# output = 0x3610a686

which will encode each 8 bits of the string correctly.

1
votes

for python 3 your binary in python3 should be b'10001', should be prefixed with b or B to denote bytes literal:

In [11]: a=b'10000011110'

In [17]: hex(binascii.crc32(a))
Out[17]: '0xfc8e2013'