1's Complement

Python Programming

Python Programming Examples

#!/usr/bin/evn python

# Bitwise shitf left '1' at '16' position
mod = 1 << 16

# Function to add one's complement
def onesComp(num1,num2):
    result = num1 + num2
    return result if result < mod else (result+1) % mod

n1 = 0b1010001111101101
n2 = 0b1000100110110101
result = onesComp(n1,n2)

# Print values upto 16 bit
print('''\
  {:016b}
+ {:016b}
------------------
  {:016b}'''.format(n1,n2,result))



#***** Output *****
  1010001111101101
+ 1000100110110101
------------------
  0010110110100011

Learn more about Bitwise Operators