手动添加十六进制数字的数字

时间:2014-03-23 14:31:09

标签: python hex

我应该编写一个代码,它以十六进制数为基数获取两个数字并计算它们的总和而不转换基数,这意味着它应该以十六进制数计算它,例如:

     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 个答案:

答案 0 :(得分: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))