HomePagev2 Forums Python Discussions Bitwise Operators

  • Bitwise Operators

     Trever Ehrlich updated 2 years ago 2 Members · 2 Posts
  • Badri Rajasekhar Reddy Rajasekhar Reddy

    Member
    September 11, 2020 at 5:08 pm

    Bitwise operators:

    In Python, Bitwise operators are used to perform Bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit and it’s work only on integers.

    for example:

    1.  &  (Bitwise AND) Operator copies a bit to the result if it exists in both operands  example :(a & b) (means 0000 1100)
    2.   |  (Bitwise OR) It copies a bit if it exists in either operand.
    3.   ^ (Bitwise OR) It copies the bit if it is set in one operand but not both.
    4.   ~  (Bitwise NOT) It is unary and has the effect of ‘flipping’ bits.

    example :

    a = 60            # 60 = 0011 1100 
    b = 13            # 13 = 0000 1101 
    c = 0
    
    c = a & b;        
    print(c)         #output ==> 12 = 0000 1100
    
    c = a | b;        
    print(c) # output ==> 61 = 0011 1101  
    
    c = a ^ b;        
    print(c)        # output ==> 49 = 0011 0001
    c = ~a;           
    print(c)         # output ==> -61 = 1100 0011
    

    I hope you understood Bitwise Operators with this example

  • Trever Ehrlich

    Administrator
    September 11, 2020 at 7:29 pm

    I believe x ^ y is called XOR (exclusive OR). Great post – brings back memories of my computer sciences classes a few years ago!

Log in to reply.

Original Post
0 of 0 posts June 2018
Now