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

Python - convert signed int to bytes

这段代码工作正常:

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, 'big')

OverflowError: can't convert negative int to unsigned

如何在不出错的情况下转换有符号整数?

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

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

方法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)