[Python-ideas] bitwise operations on bytes

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

On Fri, 7 Aug 2009 11:19:20 pm Mark Dickinson wrote:

> > Also conceivable is using the shift operators >> and << on bytes,
> > but I personally would use that less often, and the result of such
> > an operation is ambiguous due to endianness.
> Agreed.  To make sense of the shift operators you effectively have
> to give 'position' interpretations for the individual bits, and
> there's no single obvious way of doing this;  for the plain bitwise
> operations this isn't necessary.

To me, the single obvious meaning of left- and right-shift is to shift 
to the left and the right :)


b"abcd" >> 8
=> "abc"

b"abcd" << 8 
=> "abcd\0"

which would have the benefit of matching what ints already do:

>>> [hex(ord(c)) for c in "ABCD"]
['0x41', '0x42', '0x43', '0x44']
>>> n = 0x41424344
>>> hex(n >> 8)
>>> hex(n << 8)

I'm not sure what other "obvious" meanings you could give them. Have I 
missed something?

Steven D'Aprano

More information about the Python-ideas mailing list