share_title="Look at this page from SethMB.xyz"
share_description="https://sethmb.xyz/sixth/CompSci/Theory/TwosComplement/"
author="@saluki@fosstodon.org"
Two’s complement is a system that allows a binary number to be reversibly converted into a number with an equivalent value but negative.
A fairly rudimentary representation of this algorithmically is as follows. It isn’t perfect and has flaws - but it does the job a decent chunk of the time. Issues are included in the comments.
defFindComplement(inValue):# Expect the input to be a positive binary integerinValue="0"+inValue#print(inValue)# Invert each bitinValue=list(inValue)outValue=[]forbitininValue:ifbit=="0":bit="1"elifbit=="1":bit="0"outValue+=bit#print(outValue)# Add 1 to the numberifoutValue[-1]=="0":outValue[-1]="1"# Only works if the number is even. Not perfect.print("Two's complement is: "+str(outValue))inV=input("Enter binary number to complement: ")FindComplement(inV)