Advertisement
jabela

TwosComplement

Aug 27th, 2018
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.54 KB | None | 0 0
  1. def twos(twos):
  2.     if len(twos)!=8:
  3.         print("Invalid length")
  4.  
  5.     for i in twos:
  6.             if int(i) > 1:
  7.                 print("invalid value")
  8.  
  9.     if twos[0]=="1":
  10.         print("negative twos complement")
  11.         twos = int(twos, 2)
  12.         decimal = 256 - twos
  13.         final_num = -decimal
  14.         return(final_num)
  15.  
  16.     else:
  17.         print("positive twos complement")
  18.         number = int(twos,2)
  19.         return(number)
  20.  
  21. print(twos("11110011"))
  22.  
  23. # Check with http://www.convertforfree.com/twos-complement-calculator/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement