(转)python之from_bytes、to_bytes

时间:2022-04-21 15:23:54

原文:https://blog.csdn.net/PYTandFA/article/details/78741339

https://python3-cookbook.readthedocs.io/zh_CN/latest/c03/p05_pack_unpack_large_int_from_bytes.html

首先我们来看两个__builtin__函数

num1 = int.from_bytes(b'12', byteorder = 'big')
num2 = int.from_bytes(b'12', byteorder = 'little')
print('(%s,'%'num1', num1, '),', '(%s,'%'num2', num2, ')')
result:(num1, 12594 ), (num2, 12849 )
byt1 = (1024).to_bytes(2, byteorder = 'big')
byt2 = (1024).to_bytes(10, byteorder = 'big')
byt3 = (-1024).to_bytes(10, byteorder= 'big')
lis1 = ['byt1', 'byt2', 'byt3', 'byt4']
lis2 = [byt1, byt2, byt3, byt4]
lis3 = zip(lis1, lis2)
dic = dict(lis3)
print(dic)
result:
byt1': b'\x04\x00'
byt2': b'\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00'
byt3': b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
byt4': b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'int.from_bytes()功能是将字节转化成int型数字'12'如果没有标明进制,看做ascii码值,'1' = 49 = 0011 0001, '2' = 50 = 0011 0010,如果byteorder = 'big', b'12' = 0010 0001 0010 0010 = 12594;如果byteorder = 'littlele', b'12' = 0011 0010 0011 0001 = 12849。第三个参数为signed表示有符号和无符号;(number).to_bytes()功能将整数转化成byte
(1024).to_bytes(10, byteorder = 'big'),一个int型,4字节。1024 = 0000 0000 0000 0000 0000 0100 0000 0000,由于给定的是10,所以凑齐10个字节,高位用6个
0000 0000占位,如果最后用16进制表示,1024 = b'\x00\x00\x00\x00\x00\x00\x00\x00x04\x00
在看一个例子:
byt3 = (-1024).to_bytes(10, byteorder= 'big', signed = 'true'),由于signed = 'true', -1024 = 1000 ...(11) 0000 0000 0000 0000 0000 0100 0000 0000,符号位为1,...省略了
11个0000,由于负数由补码表示,所以先求-1024的反码,即符号位不变,其他位0变1,1变0,得:1111 ...(11) 1111 1111 1111 1111 1111 1011 1111 1111,对反码 + 1,得到补码:
1111 ...(11) 1111 1111 1111 1111 1111 1100 0000 0000,用16进制表示:\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00
再举个例子:
num3 = int.from_bytes(b'\xf3\x25', byteorder = 'little')
f3 = 243(10进制)= 1111 0011,25 = 37(10进制)= 0010 0101,byteorder = 'little',字节的低位占主要作用, 得到:0010 0101 1111 0011,得到十进制:9715
num3 = int.from_bytes(b'\xf3\x25', byteorder = 'big', signed = 'true')
f3 = 243(10进制)= 1111 0011,25 = 37(10进制)= 0010 0101,byteorder = 'big',字节的高位占主要作用, 得到:1111 0011 0010 0101,signed = 'true',说明有符
号,而且高位为1,所以用补码:1000 1100 1101 1011 即:-3291