[Python-ideas] bitwise operations on bytes

Terry Carroll carroll at tjc.com
Fri Dec 22 00:47:36 CET 2006

I'll start.

I would like to be able to have the capability of doing bitwise operations 
on a string-like field.  For this example, I'll use strings, but as I 
understand it, the planned byte type would probably be more appropriate.

An example.  Suppose I have a string (say, read in from a binary file) 
that has a 4-byte field in it.  Bit 11 indicates whether the accompanying 
data is in glorped form (something I'm just making up for this example).

For example, if the field has 0x000480c4, the data is not glorped.  
If the data is glorped, bit 11 would be on, i.e., 0x001480c4.

Let's say I want to turn on the glorp bit; what I have to do now:

GLORPED = 0x10
newchar = chr(ord(flags[1]) | GLORPED)
flags = flags[0] + newchar + flags[2:]


What I'd like to be able to do is something like:

GLORPED = "x\00x\10x\00\x00"
flags = flags | GLORPED

I've actually run into this, on a read-only side, in reading and 
interpreting MP3 files.

As I said, this is probably better for a bytes object than string.

More information about the Python-ideas mailing list