Why does a Python bytearray work with value >= 256

binary, byte, python

Solution

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`. In Python 3, you would get an error message:

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

The following code works in Python 2 or Python 3; note that I'm passing an 8 bit number, so it's in range.

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

output

bytearray(b'\xff')

Problem

The Python documentation for bytearray states: The bytearray type is a mutable sequence of integers in the range 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` ``` ba = bytes([0b111111111]) print '%s' % (ba) ``` The 9 bit binary number is printed as decimal 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.

Original source