pythonbit-manipulationlow-levelhigh-level

What are the advantages to using bitwise operations over boolean operations in Python?


I'm having trouble understanding just why I would want to use bitwise operators in a high-level language like Python. From what I have learned of high- vs low-level languages is that high-level ones are typically designed to that you don't have to worry too much about the machine code going into a computer. I don't see the point of manipulating a program bit-by-bit in a language that, to my knowledge, was designed to avoid it.


Solution

  • If you want a concrete example of bitwise operators being used in the standard library, just look at the re library. According to the API, the flags are supposed to be bitwise ORed together.

    This allows you to pass a large number of options in a single argument. Consider the following options:

    re.compile(expression,re.I | re.M | re.X)
    

    vs.

    re.compile(expression,ignorecase=True,multiline=True,verbose=True)
    

    I think we can agree that the first version is a lot more compact at least.


    You may be thinking "Well, I like the second better -- after all, it is more explicit!" ... And you might have a case for that. But what if you had a colleague who generated a binary file in C and he told you that the header of the file contained a 32 bit integer field and that integer field stores the flags necessary to decode the rest of the file? You, being a reasonable person want to work with the file in a high-level language where you can manipulate the data easily and efficient so you choose python. Now I bet you're glad you can do bitwise operations as to keep yourself from needing to use C to decode/analyze your file.