Author Topic: Binary,One's,Two's Complement conversion  (Read 483 times)

0 Members and 1 Guest are viewing this topic.

Offline $Clone

  • Peasant
  • *
  • Posts: 86
  • Cookies: 5
  • $---Shadowalker---$
    • View Profile
Binary,One's,Two's Complement conversion
« on: December 18, 2015, 07:14:18 pm »
hey there!...... for those learning about how negative numbers are computed in your computer am sure you have
heard of one's,two's complement......https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html
So i did a little python script to do all this conversions.Please Note i know some of this stuff can be done through |,&,^ operators not to mention python built in functions i just did this to show how the inner workings of the conversions can be done as per me  ;)
Before taking a look check out http://artsites.ucsc.edu/ems/music/equipment/computers/bits_bytes/bits_bytes.html

Code: (Python) [Select]

#try 1-127......(-ve)
#e.g.-13,-16,-17,-5 etc
print"-----------------------------------------------------"
print"Change from binary to one's and two's complement"
print"-----------------------------------------------------"
print"-----------------------------------------------------"
try:
result=[]
numb=input("Enter number:")
numb=abs(numb) #convert to positive number
except:
print("Digits only!")
else:
#get binary form you can use bin()....no biggy!
while numb!=0:
if numb%2==0:
result.append(0)
numb=numb//2
else:
result.append(1)
numb=numb//2
result.reverse() # get reversed form
sizeL=len(result)

#change to hex
if sizeL!=4:
size=8-sizeL
else:
size=4
for i in range(size):
result.insert(i,0)
print "(+)Binary form:",str(result).strip("]").strip("[").replace(",","")
#convert to one's complement
for i in range(8):
if result[i]==1:
result.pop(i)
result.insert(i,0)
else:
result.pop(i)
result.insert(i,1)
print "(+)One's complement:",str(result).strip("]").strip("[").replace(",","")
#convert to two's complement
twoC=range(8)
twoC.reverse()
for i in twoC:
if int(result[i])==1:
result.pop(i)
result.insert(i,0)
else:
result.pop(i)
result.insert(i,1)
break;
print "(+)Two's complement:",str(result).strip("]").strip("[").replace(",","")
print"-----------------------------------------------------"
print"\t\t\tEND"
print"-----------------------------------------------------"



Don't be dumb to try -257  ::) try 1 to any 8bits form! .....but can be modified to have more bits.......
The largest number you can represent with 8 bits is 11111111, or 255 in decimal notation,00000000 is the smallest. You can only represent 256 things with a byte.
« Last Edit: December 18, 2015, 07:40:29 pm by $Clone »