Python - 将有符号整数转换为字节

问题描述 投票:0回答:2

此代码运行良好:

an_int = 5
a_bytes_big = an_int.to_bytes(2, 'big')
print(a_bytes_big)

但是当我将 an_int 更改为 -5 时,出现以下错误:

a_bytes_big = an_int.to_bytes(2, '大')

OverflowError:无法将负 int 转换为无符号

如何转换signed int 而不出现错误?

python byte converters
2个回答
5
投票

错误消息很清楚,如果您的值包含符号,则在将其转换为字节时需要传递

signed =True

an_int = -5
a_bytes_big = an_int.to_bytes(2, 'big', signed = True)
print(a_bytes_big)

3
投票

方法 to_bytes 采用第三个参数:

signed
: 所以你可以将代码修改为:

an_int = -5
a_bytes_big = an_int.to_bytes(2, 'big', signed=True)
# or
a_bytes_big = an_int.to_bytes(2, 'big', True)
© www.soinside.com 2019 - 2024. All rights reserved.