>>> print binascii.crc32("hello world")
222957957
>>> crc = binascii.crc32("hello")
>>> crc = binascii.crc32(" world", crc) & 0xffffffff
>>> print 'crc32 = 0x%08x' % crc
crc32 = 0x0d4a1185
>>> crc
222957957
为了保证跨平台,可以在crc结果上& 0xffffffff。原因如下:
Changed in version 2.6: The return value is in the range [-2**31, 2**31-1] regardless of platform. In the past the value would be signed on some platforms and unsigned on others. Use & 0xffffffff on the value if you want it to match Python 3 behavior.
Changed in version 3.0: The return value is unsigned and in the range [0, 2**32-1] regardless of platform.
二进制转换
binascii.b2a_hex(data)和binascii.hexlify(data):返回二进制数据的十六进制表示。每个字节被转换成相应的2位十六进制表示形式。因此,得到的字符串是是原数据长度的两倍。
binascii.a2b_hex(hexstr) 和binascii.unhexlify(hexstr):从十六进制字符串hexstr返回二进制数据。是b2a_hex的逆向操作。 hexstr必须包含偶数个十六进制数字(可以是大写或小写),否则报TypeError。
>>> s = 'hello'
>>> b = b2a_hex(s)
>>> print b
68656c6c6f
>>> a2b_hex(b)
'hello'
>>> b = hexlify(s)
>>> print b
68656c6c6f
>>> unhexlify(b)
'hello'
其他实例
http://effbot.org/librarybook/binascii.htm有如下实例:
import binascii
text = "hello, mrs teal"
data = binascii.b2a_base64(text)
text = binascii.a2b_base64(data)
print text, "<=>", repr(data)
data = binascii.b2a_uu(text)
text = binascii.a2b_uu(data)
print text, "<=>", repr(data)
data = binascii.b2a_hqx(text)
text = binascii.a2b_hqx(data)[0]
print text, "<=>", repr(data)