Question

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.

Was it helpful?

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.

OTHER TIPS

There's definitely a use for bitwise operations in Python. Aside from or-ing flags, like mgilson mentions, I used them myself for composing packet headers for CAN messages. Very often, the headers for a lower-level message protocol are composed of fields that have a length that is not a multiple of 8 bits, so you would need bitwise operators if you want to change one field only.

Python being a higher-level language does not mean you cannot do low-level stuff with it!

Almost anything using transmission protocols will end up using bitwise operation at some point - a set of flags that are all true or false will normally be combined into a single byte for up to 8 flags to save on bandwidth and short of having a dictionary of 255 values to decode it - don't laugh I have seen it done in more than one language in one case with very large number of if else statments - when at most a few bitwise operations were all that was needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top