BITWISE OPERATOR IN PYTHON

Python Free Tutorial

The bitwise operator in python performs bit by bit operation on the values of the two operands. If we assign a = 5 and b = 4 then in bitwise operations a stores the value as 0101 and b as 0100. suppose we are going to do binary and (&) on a and b :

>>> a = 5
>>> b = 6
>>> print (" binary and i.e a&b is ",a&b)

OUTPUT:
 binary and i.e a&b is  4

Lets see how bitwise operator in python works :

a = 0100
b = 0101
a&b =     0100
        & 0101
       ----------
          0100  i.e. 4

These bitwise operator only make sense in terms of the binary representation of numbers. Lets go through some of the bitwise operator examples:

>>> a = 5
>>> b = 6
>>> print ("binary and i.e. a&b is:", a&b)
>>> print ("binary or i.e. a|b is:", a|b)
>>> print ("binary xor i.e. a^b is:", a^b)
>>> print ("binary not i.e. ~b is:", ~b)
>>> print ("binary leftshift of 5 by 6 units i.e. a<<b is:", a<<b)

OUTPUT:

binary and i.e. a&b is: 4
binary or i.e. a|b is: 7
binary xor i.e. a^b is: 3
binary not i.e. ~b is: -7
binary leftshift of 5 by 6 units i.e. a<<b is: 320

User think a^b as b is exponent of a i.e. a b , but these are different term. ‘^’ denotes bitwise XOR operation in python whereas ‘ ** ‘ denotes exponent

This page is contributed by Diwas & Sunil . If you like AIHUB and would like to contribute, you can also write an article & mail your article to  itsaihub@gmail.com . See your articles appearing on AI HUB platform and help other AI Enthusiast.

About Diwas

🚀 I'm Diwas Pandey, a Computer Engineer with an unyielding passion for Artificial Intelligence, currently pursuing a Master's in Computer Science at Washington State University, USA. As a dedicated blogger at AIHUBPROJECTS.COM, I share insights into the cutting-edge developments in AI, and as a Freelancer, I leverage my technical expertise to craft innovative solutions. Join me in bridging the gap between technology and healthcare as we shape a brighter future together! 🌍🤖🔬

View all posts by Diwas →

5 Comments on “BITWISE OPERATOR IN PYTHON”

  1. Do you mind if I quote a few of your articles as long
    as I provide credit and sources back to your website? My blog site is in the exact same niche as yours
    and my users would definitely benefit from some of the information you present
    here. Please let me know if this ok with you. Thanks a lot!

Leave a Reply

Your email address will not be published. Required fields are marked *