Python Bit Manipulation

Bit manipulation is used to solve variety of problems. Furthermore, its purpose is simply for optimizing code. However, every language has different implementation of bit manipulation. This piece of writing delivers the idea of python ways to do bit manipulation.

Documentation of bit manipulation in python could be found here, https://wiki.python.org/moin/BitManipulation. Furthermore there is also bitwise operator https://wiki.python.org/moin/BitwiseOperators.

Additionally, python bit manipulation has similar way with C. Basically, “&”, “|”, and “^” is just the same. However, ~ is a complement in python. Practices could be found below.

In Bit 

1001 + 0010 = 1011 0011 * 0010 = 0110 (shift to left 1) 0010 + 0010 = 0100
0110 + 0100 = 1010 0010 * 0100 = 1000 (shift to left 2) 0011 * 0011 = 1001
1000 – 0010 = 0110 0101 >> 2 = 0001 1001 ^ (~1001) = 1 (xor with negative)
0100 – 0010 = 0010 1010 ^ 0011 = 1001 0011 & (~0 << 2) = 1111

In python

>>>17 + 2 >>>3 << 1 >>>2 + 2
>>> 6 + 4 >>> 2 << 2 >>> 3 * 3
>>>8 – 2 >>>5 >> 2 >>> 9 ^ ~9 (complement)
>>> 4 – 2 >>>10 ^ 3 3 & (~0 << 2) (complement)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s