觉得有用,记得点赞
字节和列表
#转字节:
>>>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