python 数字转字节

python int类型转换为字节如下,参考官方类库文档:

int.to_bytes(lengthbyteorder*signed=False)

返回表示一个整数的字节数组。

>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 

整数会使用 length 个字节来表示。 如果整数不能用给定的字节数来表示则会引发 OverflowError

byteorder 参数确定用于表示整数的字节顺序。 如果 byteorder 为 "big",则最高位字节放在字节数组的开头。 如果 byteorder 为 "little",则最高位字节放在字节数组的末尾。 要请求主机系统上的原生字节顺序,请使用 sys.byteorder 作为字节顺序值。

signed 参数确定是否使用二的补码来表示整数。 如果 signed 为 False 并且给出的是负整数,则会引发 OverflowError。 signed 的默认值为 False

猜你喜欢

转载自www.cnblogs.com/liyuanhong/p/12133745.html