python实现十六进制补码的加减乘计算

脚本介绍:

(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))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值