(转)python之from_bytes、to_bytes
原⽂: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 = 00110001, '2' = 50 = 0011 0010,如果byteorder = 'big', b'12' = 0010 0001 0010 0010 = 12594;如果byteorder = 'littlele', b'12' = 0011 0010 00110001 = 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 01000000 0000,符号位为1,...省略了
11个0000,由于负数由补码表⽰,所以先求-1024的反码,即符号位不变,其他位0变1,1变0,得:1111 ...(11) 1111 1111 1111 1111 11111011 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 11110011,得到⼗进制: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 00100101,signed = 'true',说明有符
号,⽽且⾼位为1,所以⽤补码:1000 1100 1101 1011 即:-3291