2's compliment of binary number in python by R4R Team

Binary number

-It is a number which expressed in the base-2 numeral system,
-Binary numbers are 0 or 1.

2's compliment of the binary number-

example-

Binary number is 1010101
its 2's compliment is 101011

Binary number is 101
its 2's compliment us 011

Program-

n=int(input("Enter binary numbern"))
c1=""
while(n):
t=n%10
if t==1:
c1=c1+"0"
else:
c1=c1+"1"
n=int(n/10)

c2=str(c1[::-1])
c2=bin(int(c2,2)+int("1",2))
print("2's compliment is - "+c2)


output -

Enter binary number
1010101
2's compliment is - 0b101011

Enter binary number
101
2's compliment is - 0b11


-In this program, we take a input of number in binary format and traverse each bit and change the bit behaviour i.e. 1 to 0 or 0 to 1 using the while loop and at last we get the number in reverse order to get the ones compliment of the given binary number and then add '1' to convert ones compliment to 2's compliment.

Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!