Python bitwise operators

Python Bitwise operators

Bitwise operators are used to perform operations on binary numbers. Bitwise operators with Python are as follows.


OperatorOperation
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise NOT
<<Bitwise Zero fill LEFT SHIFT
>>Bitwise Zero fill RIGHT SHIFT


Bitwise AND operator

Values are specified in decimal number system and the operation is performed on it's corresponding binary number system.


Sets each of the bit to 1, when both the bits are 1. Otherwise reset to 0.



AND truth table



Following are the codes to perform bitwise AND operation in Python.

Program


>>> 3 & 1
1

Explanation:-

Bitwise AND logic operation



>>> 3&3
3
>>> 2&1
0
>>> 3&2
2
>>> 7&3
3



Bitwise OR operator

Sets each of the bit to 1, when one of the two bits or both the bits are 1. Reset to 0 when both are 0.


OR truth table



Following are the codes to perform bitwise OR operation in Python.


Program

>>> 3 | 1
3

Bitwise OR operation


>>> 3|3
3
>>> 2|1
3
>>> 3|2
3
>>> 4|3
7


Bitwise XOR operator

Sets each of the bit to 1, when one of the two bits are 1. If both are 1 or both are 0 it reset to 0.


XOR truth table



Following are the codes to perform bitwise XOR operation in Python.


Program

>>> 3^1
2

Bitwise XOR operation


>>> 3^3
0
>>> 2^1
3
>>> 3^2
1
>>> 7^3
4


Bitwise NOT operator

Inverts all the bits.     Following are the codes to perform bitwise NOT operation in Python.


Program


>>> ~1
-2
>>> ~-1
0
>>> ~-3
2
>>> ~-9
8
>>> ~9
-10


Bitwise Zero fill LEFT SHIFT operator

Shifts the bit toward left by pushing the 0's to the right side and discarding leftmost bits.


The number of 0's to be pushed towards right to perform left shift is specified by us.


Syntax:-
integer_value_to_be_shifted << How_many_bits_to_shift


Following are the codes to perform bitwise Zero fill LEFT SHIFT operation in Python.

Program


>>> 1<<1
2

Bitwise Zero fill LEFT SHIFT operation


>>> 1<<3
8
>>> 3<<1
6
>>> 4<<1
8
>>> 4<<2
16


Bitwise Zero fill RIGHT SHIFT operator

Shifts the bit toward right by pushing the 0's to the left side by discarding rightmost bits.


The number of 0's to be pushed towards left to perform right shift is specified by us.


Syntax:-
integer_value_to_be_shifted << How_many_bits_to_shift


Following are the codes to perform bitwise Zero fill LEFT SHIFT operation in Python.


Program


>>> 3>>1
1

Bitwise Zero fill RIGHT SHIFT operation


>>> 3>>2
0
>>> 3>>3
0
>>> 6>>1
3
>>> 6>>3
0
>>> 7>>1
3



Conclusion

Bitwise operators are used to perform operations on binary numbers. Bitwise operators with Python are as follows.

Bitwise AND, OR, XOR, NOT, Zero fill LEFT SHIFT, Zero fill RIGHT SHIFT are the bitwise operators in Python.





Previous                          Next

If you have any query, feel free to ask.

Post a Comment

If you have any query, feel free to ask.

Post a Comment (0)