Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python bitwise operators

  • Bitwise operator:  In python, the bitwise operator is used to performing the bitwise calculations on integers.
  • It can apply to boolean type also.
  • It will be converted into binary numbers and bitwise operations in integers first on that binary number.
  • As it performs the bit to bit operations the name is called a bitwise operator.
  • There are six types of bitwise operators in python they are:
  1. &   And.
  2. |      or.
  3. ^      xor.
  4. ~     bitwise not
  5. >>   right shift.
1.And(&): If both bits are then it returns true, else false.
syntax: (x&y).

Example: write a python program for integer values using And operator.

  1. x=4
  2. y=5
  3. print(x&y)
output: 4


2. or(|):  If any one of the bits is true then the result is true, else false.
           It is denoted by the symbol "|".
syntax:(x|y).

Example: write a python program for integer values using or. 

  1. x=10
  2. y=5
  3. print(x|y)
output: 15


3. xor(^): when both bits are different returns true, else false.
It is denoted by the "^" symbol.
syntax:(x^y)

Example: write a python code for integers using xor operator.

  1. x=1
  2. 2
  3. print(x^y)
output: 3


4. Bitwise not (~): It is the complement of the bit if the bit is 1 if the result is 0, if the bit is 0 then it result is 1.
It is denoted by the "~" symbol.
syntax:(~x)

Example: write a python code for bool type using bitwise not operator.

  1. x=true
  2. print(~true)
output: -2.



5.Right shift(>>): It shifts one bit right and fills the left side vacant cells with significance values.
It is denoted by ">>".
syntax:(x>>).

Example: Write a python program using the right shift operator.

  1. x=11
  2. y=2
  3. print(x>>y).
output: 2



6.Left shift(It shifts one bit left and the right side vacant cells fill with 0.
It is denoted by the "
syntax:(x

Example: write a python code for int values using the left shift operator.

  1. x=11
  2. y=2
  3. print(x
output:44




This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

Python bitwise operators

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×