python bitwise operations


Bitwise operations are important and are used in setting up flags, they are used in Cryptography and compression algorithms,  graphics etc. You may not be using in most of your code they they are fast and sometimes speed up certain operations significantly.

Bitwise operators

Operator Description Syntax
& Bitwise AND x & y
| Bitwise OR x | y
~ Bitwise NOT ~x
^ Bitwise XOR x ^ y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

 


Below are some examples of converting a number to bitwise notation

  • bin function takes a number (int NOT string) and returns String
  • int function takes a string and base (2 in our case as its binary number to convert to int)
  • int can take 16 as base to convert hexadecimal number to int.
>>> bin(4)
'0b100'
>>> bin (-4)
'-0b100'
>>> 
>>> int('-100',2)
-4
>>> 
>>> int('1001',2)
9

>>> int('F',16)  ## hexadecimal
15


Why do we need bitwise operations?

  • Some operations are faster using bitwise operations
  • Low level programming it’s widely used in C
  • For interviews!!

 


Some Important things to remember about bitwise operations:

  • each shift left operation will multiply number by 2, like 100 becomes 100<<1 will be come 200, 100<<3 will become 800
  • each shift right operation will divide the number by half, 100>>1 will become 50, 100>>2 will become 25, 100>>3 will become 12 (returns int)

 


Some practical questions:

How to multiply by 5 without using *?

>>> x=5
>>> (x<<2) +x
25
>>> 

 

How to check if a number is odd?

>>> 7 & 1 
1
>>> 8 & 1 
0

 

leetcode question: Given an integer “n”, write a function to determine if it is a power of two.

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        z=bin(n)
        x=z[2:]
        print (type(x))
        if(x=='1'):
            return True
        if (x[0]=='1' and x.count('0')==(len(x)-1)):
            return True
        return False

 

+ There are no comments

Add yours