Python binary operators are pretty much the same as in any other language, however I notice most programmers tend to waste a lot of memory by creating lots and lots of properties say in DB tables, or Objects and using the wrong datatypes. I think its elegant to use the concept of binary flags, for example, if you have an object that has around 8 or 16 boolean properties, you can store their state in 1 byte or 2 bytes (1 char or 2 char fields), and turn on/off the bits on those fields.
Usually, if you have a binary field, and you want to, turn on bits, toggle bits, and check bits, you do the following.
Suppose “config” is an 8 bit number, and you want to modify this bits individually, say config=4 (0b100) and you want to turn on the rightmost bit to have 0b101 (which is a 5) you could do the following
>>> #Uses the | operator ... def turnBitOn(config, binaryFlag): ... return config | binaryFlag ... >>> config = 4 >>> config = turnBitOn(config,1) >>> print config 5
If you want to check if a Bit is turned on, just use the “&” operator, if the result is the same as the bit you’re comparing, then its turned on.
>>> def checkBit(config,binaryFlag): ... return binaryFlag == config & binaryFlag ... >>> print checkBit(config,1) True >>> print checkBit(config,2) #checks 0b010 in 0b101 False
What if you just want to toggle a bit, no matter what’s in there?
Just use binary XOR, the “^” operator.
>>> def toggleBit(config,binaryFlag): ... return config ^ binaryFlag ... >>> print config 5 >>> config = toggleBit(config,1) >>> print config 4 >>> config = toggleBit(config,1) >>> print config 5
And now, the last basic operation would be to turn off a bit. For this, you should do a NAND operation. The Binary Not in python as in most programming languages is the “~” operator. This is how you can use it to turn off bits.
You have to do it in conjunction with the & operator, sort of doing a NAND
>>> 5 & (~1) 4 >>> 5 &~ 1 4
So we could define our turnOffBit function as follows:
>>> def turnOffBit(config,binaryFlag): ... return config & (~binaryFlag) ... >>> print config 5 >>> config = turnOffBit(config,1) >>> print config 4 >>> config = turnOffBit(config,1) >>> print config 4
Hope this makes a good reference for those trying to make the most out of their bytes.