python的数字转字节和字节转数字【有正负】

本文详细介绍了Python中字节与数字之间的转换方法,包括如何将列表转换为字节,以及如何将字节转换回列表。同时,深入探讨了整数转字节和字节转整数的过程,特别是对于负数的处理方式,以及如何使用Python内置函数实现这些转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

觉得有用,记得点赞

字节和列表

#转字节:
>>>x= [1,15,17]
>>>x = bytearray(x)
>>>print(x)
bytearray(b'\x01\x0f\x11')

#转列表
>>>x = bytearray(b'\x01\x0f\x11')
>>>list(x)
[1, 15, 17]

对于小于零的数字或者字节,转换时python默认会先将其转换为反码

数字转字节
int.to_bytes(length,byteorder,*signed)

整数.to_bytes(字节长度,字节顺序,*字节符号)
字节顺序:
		高位在前:'big'		低位在前:"little"
最高位为符号:
		有符号:True			无符号:False


如:
>>>(1024).to_bytes(2,'big')
b'\x04\x00'

>>>(-1024).to_bytes(2,'big')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
OverflowError: can't convert negative int to unsigned

带入有符号的参数:
>>>(-1024).to_bytes(2,'big',signed=True)
b'\xfc\x00'
负数产生的是原来的反码
字节转数字
int.from_bytes(type,bytes,bytesorder,signed=False)

例如:
>>>int.from_bytes(b'\xfc\x00',byteorder='big',signed=True)
-1024

负数产生的是原来的反码

不过我想 你们都只想要这个

# 有符号的数字 转 最高位带 符号的字节
>>>x=-32767
>>>x =  -(32768 + x) if x < 0 else x
>>>x = x.to_bytes(2,'big',signed = True)
>>>print(x)
b'\xff\xff'

# 定义成函数
def int2hex(num, bits = 16):
	# 最大值
	max_val = pow(2, bits - 1)
	# 转换
	num = -(max_val + num) if num < 0 else num
	num = num.to_bytes(int(bits / 8),'big',signed = True)
	return num

最高位有符号的字节 转为 带符号的数字
>>>x= b'\xff\xff'
>>>x = int.from_bytes(x,byteorder='big',signed=True)
>>>x= x if x>0 else -(32768 + x)
>>>print(x) 
-32767

上面的 32768 对应两个字节 的最高位 2^15

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酸奶可乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值