how to perform bitwise operation in python code example
Example 1: python bitwise operators methods
OPERATOR DESCRIPTION SYNTAX FUNCTION IN-PLACE METHOD
& Bitwise AND a & b and_(a, b) __and__(self, other)
| Bitwise OR a | b or_(a, b) __or__(self, other)
^ Bitwise XOR a ^ b xor(a, b) __xor__(self, other)
~ Bitwise NOT ~ a invert(a) __invert__(self)
<< Bitwise L shift a << b lshift(a, b) __lshift__(self, other)
>> Bitwise R shift a >> b rshift(a, b) __irshift__(self, other)
Example 2: write a program to input a number and display its double and half values using shift operator in python
print("Hi \nThis is a basic calculator \nwhich doubles or divides into half the value entered in it")
i = int(input("pls enter your number:\n"))
print("what do you want to do? \nwarning: \nenter only the alphabet of the option and no symbols.")
print("you can enter both the options alphabet to get both the values")
print("This program gives and takes only integer value of double, half and input")
opt = input("options:- \na.double\nb.half\n")
if opt == "a":
j = i << 1
print("double", j)
elif opt == "b":
k = i >> 1
print("half:", k)
elif opt == "ab" or opt == "a b" or opt == "ba" or opt == "b a" or opt == " ab" or opt == "ab " or opt == " ab " or opt == " a b" or opt == "a b " or opt == " a b ":
j = i << 1
k = i >> 1
print("number:", i)
print("double:", j)
print("half:", k)
else:
print("inputs are wrong")
exit()
Example 3: bitwise operators python
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<<
Example 4: write a program to input a number and display its double and half values using shift operator in python
print("Hi \nThis is a basic calculator \nwhich doubles or divides into half the value entered in it")
a = int(input("pls enter your number:\n"))
b = a << 1
c = a >> 1
print("number:", a, "\ndouble:", b, "\nhalf:", c)