gpt4 book ai didi

python - 如何在 Python 3 中以字节显示大于 255 的值

转载 作者:行者123 更新时间:2023-11-28 21:53:48 27 4
gpt4 key购买 nike

信不信由你,我到处寻找这个答案。如何将大于 255 的值转换为 Python 3 中的 bytes 对象。我认为这需要一个字节字符串,但我不确定。

例子:

n = 257 
print(n) #Prints 257
n = bytes([n])
print(n) #ValueError: bytes must be in range(0, 256)

最佳答案

int 对象可以使用 to_bytes 方法转换为字节。但是,您必须指定字节数和字节顺序。

例子:

n.to_bytes(2, 'little')  # b'\x01\x01'

关于python - 如何在 Python 3 中以字节显示大于 255 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25499719/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com