python的from_bytes属性_(转)python之from_bytes、to_bytes

本文介绍了Python的int.from_bytes和to_bytes函数,详细解释了这两个函数的作用和使用方法,包括字节顺序、有符号和无符号转换,并通过示例展示了如何将字节转换为整数以及整数转换为字节。
摘要由CSDN通过智能技术生成

原文: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值