[Python-ideas] bitwise operations on bytes

Steven D'Aprano steve at pearwood.info
Sat Aug 8 07:51:26 CEST 2009

On Fri, 7 Aug 2009 09:43:54 pm Tal Einat wrote:

> You can already do bitwise operations on bytes,

Are you sure about that? I tried looking it up in the docs, but
python.org is down at the moment, so excuse me if I've missed something
obvious.

In Python 3.0:

>>> b'ABCD' & 255
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'bytes' and 'int'
>>>
>>> b'ABCD' & b'\xff'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'bytes' and 'bytes'

Have I missed something?

> As I see it, the major underlying problem here is that
> byte-arrays are immutable, since what you really want is to be able
> to change a single byte of the array in-place.

I'm not speaking for the original poster, but for myself, not
necessarily. While it would be nice to be able to flip bits directly,
I'd be happy with bitwise operators to return new instances, as they
currently do for ints. Something like:

# not actual code
>>> bb = bytes("ABCD")
>>> bb &= b"\xff\0"
>>> bb
b"C\0"

This could work for bit-flipping operations, although I'd welcome an
easier to use API:

# still not actual code
>>> bb = bytes("ABCD")
>>> bb |= (2**5)*256  # set the 5th bit of the 2nd byte
>>> bb
b"ABcD"

--
Steven D'Aprano