0

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 ?

7
  • you need a hex output right? Commented Jun 1, 2015 at 13:57
  • Hex output is ok, I think I can convert it to whatever I need. Commented Jun 1, 2015 at 13:59
  • what is the maximum length of binary data? Commented Jun 1, 2015 at 14:00
  • binascii.crc32(binascii.b2a_hex('10000101010101001')); Out[10]: 945985288 Commented Jun 1, 2015 at 14:07
  • binascii.crc32(binascii.b2a_hex(my_binary_string)) : TypeError: 'str' does not support the buffer interface Commented Jun 1, 2015 at 14:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.