Python byte转integer/string

需求:将形如’y\xcc\xa6\xbb’byte字符串转化为integer或者string

方法1 导入struct
import struct
struct.unpack("<L", "y\xcc\xa6\xbb")[0]
方法2 python3.2及以上

byte串采取大端法:

int.from_bytes(b'y\xcc\xa6\xbb', byteorder='big')

若采取小端法,则:

int.from_bytes(b'y\xcc\xa6\xbb', byteorder='little')
方法3 借助十六进制转换

大端法:

s = 'y\xcc\xa6\xbb' 
num = int(s.encode('hex'), 16)

小端法:

int(''.join(reversed(s)).encode('hex'), 16)
方法4 使用array
import array 
integerValue = array.array("I", 'y\xcc\xa6\xbb')[0]

其中I用于表示大端或小端,且使用此方法要注意自己使用的python版本。

方法5 自己写函数实现

如:

sum(ord(c) << (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))

又如:

def bytes2int( tb, order='big'):
    if order == 'big': seq=[0,1,2,3]
    elif order == 'little': seq=[3,2,1,0]
    i = 0
    for j in seq: i = (i<<8)+tb[j]
    return i
字符数组转换成字符串
>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring() 
'\x11\x18y\x01\x0c\xde"L'

参考链接


发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注