脚本介绍:
(1)实现十六进制补码加减乘计算;
(2)使用方法。把本脚本命名为calc.py。在terminal中输入python calc.py string。即可根据输入的string做计算。如,输入python calc.py 50x10*50x0f,既可以得到100x310。这里的输入数据和输入都是用补码形式计算的。0x表示输入数是16进制,0x前的数表示该数的位宽,0x后面的数是参与运算的数值。这个例子就实际上就是计算-16*15,计算结果为-240。
(3)这里使用了sys,argv,str,int,eval,字符串的分割和拼接等。
import sys
print("This is a two's complement calculator\n")
op_str = sys.argv[1]
#get the operator and operand
if "+" in op_str:
op_num = op_str.split("+")
op_a = op_num[0]
op_b = op_num[1]
op_s = "+"
elif "-" in op_str:
op_num = op_str.split("-")
op_a = op_num[0]
op_b = op_num[1]
op_s = "-"
elif "*" in op_str:
op_num = op_str.split("*")
op_a = op_num[0]
op_b = op_num[1]
op_s = "*"
#obtain the operand and translate it to int
op_a_l = op_a.split("0x")
op_a_width = int(op_a_l[0])
op_a_num = int(op_a_l[1],16)
op_b_l = op_b.split("0x")
op_b_width = int(op_b_l[0])
op_b_num = int(op_b_l[1],16)
#two's complement -> signed decimal
if op_a_num >= 2**(op_a_width-1) :
op_a_real = op_a_num - 2**op_a_width
else:
op_a_real = op_a_num
if op_b_num >= 2**(op_b_width-1) :
op_b_real = op_b_num - 2**op_b_width
else:
op_b_real = op_b_num
#calculate the result width
if op_s == "-" or op_s == "+":
if op_a_width > op_b_width:
op_result_width = op_a_width+1
else:
op_result_width = op_b_width+1
else:
op_result_width = op_a_width + op_b_width
*use eval function
op_result_str = str(op_a_real) + op_s + str(op_b_real)
op_result_num = eval(op_result_str)
#signed decimal -> two's complement
if op_result_num <0:
op_result_real = op_result_num + 2**op_result_width
else:
op_result_real = op_result_num
#translate to hex
op_result_hex = hex(op_result_real)
#connect strings
op_result= str(op_result_width)+op_result_hex
#print the reuslt
print("The result is %s"%(op_result))