简体   繁体   English

为什么 Python 字节数组的值 >= 256

[英]Why does a Python bytearray work with value >= 256

The Python documentation for bytearray states:bytearray的 Python文档指出:

The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. bytearray 类型是 0 <= x < 256 范围内的整数的可变序列。

However the following code suggests values can be >= 256. I store a 9 bit binary number which has a maximum value of: 2^9-1 = 512-1 = 511但是,以下代码建议值可以 >= 256。我存储一个 9 位二进制数,其最大值为: 2^9-1 = 512-1 = 511

ba = bytes([0b111111111])
print '%s' % (ba)

The 9 bit binary number is printed as decimal 511: 9 位二进制数打印为十进制 511:

[511]

I don't know what the intended behavior is, but I assumed the most significant bit(s) would be dropped to give an 8 bit number.我不知道预期的行为是什么,但我假设最高有效位将被删除以给出 8 位数字。

You aren't actually creating a bytearray or a bytes object, you're just creating a string containing '[511]' , since bytes in Python 2 is just a synonym for str .您实际上并没有创建bytearraybytes对象,您只是创建了一个包含'[511]'的字符串,因为 Python 2 中的bytes只是str的同义词。 In Python 3, you would get an error message:在 Python 3 中,您收到一条错误消息:

ValueError: byte must be in range(0, 256)

The following code works in Python 2 or Python 3;以下代码适用于 Python 2 或 Python 3; note that I'm passing an 8 bit number, so it's in range.请注意,我正在传递一个 8 位数字,因此它在范围内。

ba = bytearray([0b11111111])
print(repr(ba))

output输出

bytearray(b'\xff')

code:代码:

a = 511
byte = a.to_bytes(byte length goes here, 'little')

to decode:解码:

a = int.from_bytes(byte, 'little')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM