Skip to main content

Add two numbers using bitwise operators in python

Python program for Add two numbers using bitwise operators. Here more information.

#  Python 3 program for
#  Add two numbers using of bitwise operators
class NumberAddition :
	#  Add two numbers
	def addition(self, a, b) :
		#  Display given numbers
		print("\n [(", a ,") + (", b ,")] ", end = "",sep = "")
		#  Auxiliary variable which are store the carry bit result
		carry = 0
		#  Executing loop, until b value is not zero
		while (b != 0) :
			#  Get carry bits of a & b
			carry = a & b
			#  Sum of bits of a ^ b
			a = a ^ b
			#  Shift the carry bit by one bit in left side
			b = carry << 1
		
		#  Display add result
		print(" : ", a, end = "")
	

def main() :
	task = NumberAddition()
	#  Test Case
	task.addition(8, 2)
	task.addition(5, 3)
	task.addition(-3, -5)

if __name__ == "__main__": main()

Output

 [(8) + (2)]  :  10
 [(5) + (3)]  :  8
 [(-3) + (-5)]  :  -8

Some special case this program are not work (such as addition( -6, 7),addition( 8, -2) etc).





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment