手动相加十六进制数字

1 投票
1 回答
1743 浏览
提问于 2025-04-17 23:32

我需要写一段代码,接收两个十六进制的数字,然后计算它们的和,而不需要把它们转换成其他进制。这意味着计算也要在十六进制下进行,比如:

     1 f 5 (A) 
+      5 a (B) 
------------- 
   = 2 4 f 

这个函数的输入示例是:

>>> add("a5", "17") 

'bc'

到目前为止,我写了这段代码,但不知道该怎么继续。我想我可以创建三个循环,一个用来加数字,一个用来加数字和字母,第三个用来加字母。

def add_hex(A,B):
    lstA = [int(l) for l in str(A)]
    lstB = [int(l) for l in str(B)]

    if len(A)>len(B):
        A=B
        B=A
    A='0'*(len(B)-len(A))+A
    remainder=False
    result=''
    for i in range(len(B)-1):
        if (A[i]>0 and A[i]<10) and (B[i]>0 and B[i]<10):
           A[i]+B[i]=result
           if A[i]+B[i]>10:
               result+='1'

1 个回答

1

根据我的经验,处理十六进制数字的加法和减法,最好的方法是使用一些额外的函数:

def dec_to_hex(number):
    rValue = ""
    hex_bits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
    while(number):
        rValue = hex_bits[number%16] + rValue
        number = number/16
    return rValue

def hex_to_dec(hex_string):
    hex_dict = {"0" : 0,
                "1" : 1,
                "2" : 2,
                "3" : 3,
                "4" : 4,
                "5" : 5,
                "6" : 6,
                "7" : 7,
                "8" : 8,
                "9" : 9,
                "A" : 10,
                "B" : 11,
                "C" : 12,
                "D" : 13,
                "E" : 14,
                "F" : 15}        
    rValue = 0
    multiplier = 1;
    for i in range(len(hex_string)):
        rValue = hex_dict[hex_string[len(hex_string)-1-i]] * multiplier + rValue
        multiplier = multiplier * 16            
    return rValue

而你的加法函数可以是

return dec_to_hex(hex_to_dec(number1) + hex_to_dec(number2))

撰写回答