4

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.

Jack
  • 10,313
  • 15
  • 75
  • 118

2 Answers2

11

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')
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
  • 2
    Also if you type `help(bytes)` in Python 2 it shows the `str` help page. – Adam Van Prooyen Oct 24 '16 at 15:04
  • So according to the error message `ValueError: byte must be in range(0, 256)`, the value 256 is allowed as well as value 0. This makes 257 possible values in a byte. Python always impresses me... – Rusty Gear Apr 27 '22 at 16:07
  • @RustyGear No, `range(0, 256)` produces 256 numbers, from 0 up to 255. Similarly, `"abcdef"[0:3]` is the string `"abc"`. Almost everything in Python uses that convention. – PM 2Ring Apr 27 '22 at 16:41
1

code:

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

to decode:

a = int.from_bytes(byte, 'little')
Yash
  • 6,644
  • 4
  • 36
  • 26