import sys
import operator
from time import sleep
class Processor:
def __init__(self):
self.bits = 40
self.stack = []
self.math = {'add': operator.add,
'sub': operator.add,
'mul': operator.mul,
'div': operator.truediv,
'lsh': operator.lshift,
'rsh': operator.rshift,
'xor': operator.xor,
'xor': operator.xor,
'mod': operator.mod,
'and': operator.and_,
'or': operator.or_
}
self.sleep = 1
self.filemode = False
def _split(self, val):
sgn = 0 if val>=0 else 1
val = abs(val)
e = 0
if type(val) not in [int, long]:
while ( str(val).split('.')[1]!='0' ) and val<1000000 and e<62:
val *= 10
e -= 1
while (val%10==0 and val>0):
val /= 10
e += 1
sgne = 0 if e>=0 else 1
e = abs(e) & ((1 << 6)-1)
val = int(round(val)) & ((1 << 24)-1)
return (sgn, int(round(val)), sgne, e )
def put(self, val):
self.stack.append(val)
def pop(self):
return self.stack.pop()
def old_to_bin(self, stack):
res = str(stack[0])+' '
mant = bin(stack[1])[2:]
while len(mant) < 26:
mant = '0'+mant
res += mant+' '+str(stack[2])+' '
e = bin(stack[3])[2:]
while len(e) < 13:
e = '0'+e
res += e
return res
def _to_bin(self,num):
if num:
sign = 1 if num<0 else 0
drob = abs(num - int(num))
num = abs(int(num))
resdrob = 1
count = 0;
while drob and count < 999:
resdrob = resdrob << 1
drob *= 2
if drob>=1:
drob -= 1
resdrob +=1
count += 1
bdrob = int(tobin(resdrob&((1<<len(bin(resdrob))-3)-1)))
tnum = num
e = 0
if num:
while tnum>1:
e += 1
tnum = tnum >> 1
e += 4095
e &= (1<<13)-1
tnum &= (1<<26)-1
st = tobin(num)[1:]
st += tobin(resdrob)[:26-len(st)]
st = st[0:25]
else:
pos = (tobin(resdrob)[1:]).find('1')
e = 4095 - (pos+1)
st = tobin(resdrob)[pos+1:pos+27]
st = st[0:25]
e &= (1<<12)-1
else:
sign,e,num,bdrob,count=0,0,0,0,26
while len(st)<26:
st += '0'
return str(sign)+' '+("%013d"%int(tobin(e)))+' '+st
def print_stack(self):
count=0
for stack in self.stack[::-1]:
print 'Stack['+str(count)+']: '+str(self._to_bin(stack))
count += 1
while count<8:
print ('Stack[%d]: 0 '+'0'*13+' '+'0'*26) % count
count += 1
def process(self, commands):
for command in commands:
if command[0] == 'put':
if command[1].isdigit():
self.put(int(command[1]))
else:
self.put(float(command[1]))
elif command[0] == 'get':
print 'Returned value: %g' % self.pop()
elif command[0] == 'copy':
val = self.pop()
self.put(val)
self.put(val)
elif command[0] == 'rev':
v1 = self.pop()
v2 = self.pop()
self.put(v1)
self.put(v2)
elif command[0] in self.math.keys():
op1 = self.pop()
op2 = self.pop()
self.put(self.math[command[0]](op1,op2))
elif command[0] == 'status':
pass
else:
print ('Wrong command')
continue
self.print_stack()
sleep(self.sleep)
if self.filemode:
raw_input()
import sys
def main():
p = Processor()
if len(sys.argv)==2:
a = [ c.split() for c in open(sys.argv[1]).read().split('\n') ]
p.sleep=0
p.filemode=True
p.process(a)
else:
p.sleep=0
p.filemode=False
while True:
print "INPUT> ",
a = raw_input()
a = [ a.split() for a in a.split(';') ]
p.process(a)
if __name__ == "__main__":
main()