Tam211
Tam211

Reputation: 743

Add numbers in hexadecimal base manually

I'm supposed to write a code which gets two numbers in hexadecimal base and calculates their sum without converting bases, which means it should calculate it in hexadecimal base for example:

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

and input example for the function would be :

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

'bc'

I've written this code so far but I have no clue how to continue, I thought that I would create three loops, one would sum numbers, the other would sum numbers and letters and the third would sum letters.

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'

Upvotes: 1

Views: 1748

Answers (1)

Maio
Maio

Reputation: 35

In my experience, the best way to approach the addition/subtraction of hex numbers was using extra functions:

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

and your add function would be

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

Upvotes: 1

Related Questions