I am trying to add two hexadecimal numbers.

def addbinary(n1,n2):

    s = ""

    carry = '0'

    for i in range(3,-1,-1):

        if (n1[i] == '1' and n2[i] == '1' and carry == '0'):

            s = '0' + s

            carry = '1'

        elif (n1[i] == '1' and n2[i] == '1' and carry == '1'):

            s =  '1' + s

            carry = '1'

        elif (n1[i] == '1' and n2[i] == '0' and carry == '0'):

            s =  '1' + s

            carry = '0'

        elif (n1[i] == '1' and n2[i] == '0' and carry == '1'):

            s =  '0' + s

            carry = '1'

        elif (n1[i] == '0' and n2[i] == '1' and carry == '0'):

            s = '1' + s

        elif (n1[i] == '0' and n2[i] == '1' and carry == '1'):

            s = '0' + s

        elif (n1[i] == '0' and n2[i] == '0' and carry == '1'):

            s = '1' + s

            carry = '0'

        elif (n1[i] == '0' and n2[i] == '0' and carry == '0'):

            s = '0' + s

    if carry == '1':

        s = '1' + s

    return s        

    

def addhex(n1):

    hextable = {

        '0' : 0000,

        '1' : 0001,

        '2' : 0010,

        '3' : 0011,

        '4' : 0100,

        '5' : 0101,

        '6' : 0110,

        '7' : 0111,

        '8' : 1000,

        '9' : 1001,

        'a': 1010,

        'b': 1011,

        'c' : 1100,

        'd' : 1101,

        'e' : 1110,

        'f' : 1111

        }

    

def main():

    """

    main function

    """

    userhex = raw_input("Enter a hexadecimal number: ")

    userhex2 = raw_input("Enter a second hexadecimal number: ")

    print addbinary(addhex(userhex.lower), addhex(userhex2.lower))  

    



if __name__ == "__main__":

    main()

Recommended Answers

All 13 Replies

Some mistakes:

(1) userhex.lower should be userhex.lower()
(2) "addhex" function is not returning any value
(3) The values of your hextable should be string i.e.

'a':"1010"  # not 'a':1010

Some mistakes:

(1) userhex.lower should be userhex.lower()
(2) "addhex" function is not returning any value
(3) The values of your hextable should be string i.e.

'a':"1010"  # not 'a':1010

Thanks cgh. But this is what get's me. why doesn't addhex work? I've been scouring over this code since Wednesday to no avail :(
addhex is supposed to translate the user's hexadecimal into a binary, then addbinary is supposed to add them.

You need to add following line at the end of the function

return hextable[nl]

so that it returns a value for addbinary() to work on.

You need to add following line at the end of the function

return hextable[nl]

so that it returns a value for addbinary() to work on.

Ok this is what I got:
When I run the code I get:
Key Error: 4fef(this is what the user typed in.)
Is it because I am using raw_input? and I can't add them because they are strings?

def addbinary(n1,n2):

    s = ""

    carry = '0'

    for i in range(3,-1,-1):

        if (n1[i] == '1' and n2[i] == '1' and carry == '0'):

            s = '0' + s

            carry = '1'

        elif (n1[i] == '1' and n2[i] == '1' and carry == '1'):

            s =  '1' + s

            carry = '1'

        elif (n1[i] == '1' and n2[i] == '0' and carry == '0'):

            s =  '1' + s

            carry = '0'

        elif (n1[i] == '1' and n2[i] == '0' and carry == '1'):

            s =  '0' + s

            carry = '1'

        elif (n1[i] == '0' and n2[i] == '1' and carry == '0'):

            s = '1' + s

        elif (n1[i] == '0' and n2[i] == '1' and carry == '1'):

            s = '0' + s

        elif (n1[i] == '0' and n2[i] == '0' and carry == '1'):

            s = '1' + s

            carry = '0'

        elif (n1[i] == '0' and n2[i] == '0' and carry == '0'):

            s = '0' + s

    if carry == '1':

        s = '1' + s

    return s        

    

def addhex(n1):

    hextable = {

        '0' : '0000',

        '1' : '0001',

        '2' : '0010',

        '3' : '0011',

        '4' : '0100',

        '5' : '0101',

        '6' : '0110',

        '7' : '0111',

        '8' : '1000',

        '9' : '1001',

        'a': '1010',

        'b': '1011',

        'c' : '1100',

        'd' : '1101',

        'e' : '1110',

        'f' : '1111'

        }

    return hextable[n1]

    

def main():

    """

    main function

    """

    userhex = raw_input("Enter a hexadecimal number: ")

    userhex2 = raw_input("Enter a second hexadecimal number: ")

    print addbinary(addhex(userhex.lower()), addhex(userhex2.lower()))  

    



if __name__ == "__main__":

    main()

addhex(hexdigit) = hextable[hexdigit], with hextable global variable. Change the name as it has nothing to do with addition. Input must be key in the table.

addhex(hexdigit) = hextable[hexdigit], with hextable global variable. Change the name as it has nothing to do with addition. Input must be key in the table.

tony I ran the code and this is what I got:

line 65 in main
print addbinary(hextable[userhex.lower()], hextable[userhex2.lower()])
TypeError: 'function' object is unsubscriptable

What does unsubscriptable mean? immutable? like a string?

It means that hextable is function and you try to use it as dictionary.

>>> def a(b):
	return b

>>> print a[1]

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    print a[1]
TypeError: 'function' object is unsubscriptable
>>>

Test addbinary from python command line to function OK, test adding by single digit hex whe you are sure addbinary is correct. It helps to define hand calculated test cases and run those to see that everything works. Alternative is to test every possible input if number of inputs is small.

TODO list for you

1) binary numbers 1..3 binary digits with binary addition working
2) longer binary digits also working
3) conversion of single hex number inputs to binary and binary addition of results
4) conversion of many longer hex numbers to binary and binary addition by resulting binary numbers
5) user input with correct try... except checking for bad inputs


TODO list for you

1) binary numbers 1..3 binary digits with binary addition working
2) longer binary digits also working
3) conversion of single hex number inputs to binary and binary addition of results
4) conversion of many longer hex numbers to binary and binary addition by resulting binary numbers
5) user input with correct try... except checking for bad inputs

I got it to at least add single binaries(some progress:P)
But how do I add longer ones?
When I tested to see if addbinary worked, it worked, but it only added the first binary number.

If a user typed in f + e, it worked.
But when I typed more than one then it doesnt recognize the number.
ex: f + e worked. 4fef + 4eee won't.
Here is what I changed:

def addbinary(n1,n2):

    s = ""

    carry = '0'

    for i in range(3,-1,-1):

        if (n1[i] == '1' and n2[i] == '1' and carry == '0'):

            s = '0' + s

            carry = '1'

        elif (n1[i] == '1' and n2[i] == '1' and carry == '1'):

            s =  '1' + s

            carry = '1'

        elif (n1[i] == '1' and n2[i] == '0' and carry == '0'):

            s =  '1' + s

            carry = '0'

        elif (n1[i] == '1' and n2[i] == '0' and carry == '1'):

            s =  '0' + s

            carry = '1'

        elif (n1[i] == '0' and n2[i] == '1' and carry == '0'):

            s = '1' + s

        elif (n1[i] == '0' and n2[i] == '1' and carry == '1'):

            s = '0' + s

        elif (n1[i] == '0' and n2[i] == '0' and carry == '1'):

            s = '1' + s

            carry = '0'

        elif (n1[i] == '0' and n2[i] == '0' and carry == '0'):

            s = '0' + s

    if carry == '1':

        s = '1' + s

    return s

 

    

    

def main():

    """

    main function

    """

    hextable = {

        '0' : '0000',

        '1' : '0001',

        '2' : '0010',

        '3' : '0011',

        '4' : '0100',

        '5' : '0101',

        '6' : '0110',

        '7' : '0111',

        '8' : '1000',

        '9' : '1001',

        'a': '1010',

        'b': '1011',

        'c' : '1100',

        'd' : '1101',

        'e' : '1110',

        'f' : '1111'

        }

    userhex = raw_input("Enter a hexadecimal number: ")

    userhex2 = raw_input("Enter a second hexadecimal number: ")

    print addbinary(hextable[userhex.lower()], hextable[userhex2.lower()])  

    



if __name__ == "__main__":

    main()

As you can see def hextable in gone. and I put the dictionary inside main, apparently that did the trick for adding single binaries. But I need to add multiple binaries.
How do I add more than one variable from hextable?
for example: I need 4fef; 4 is in the dictionary, f is too, and so is e. If I called these variables individually, it worked, but when I put them next to each other, it doesn't work anymore.:confused: even though the key is inside the dictionary.:confused:

You can lookup each nibble (hex digit) and just join the values of them together as each nibble corresponds one to one to binary digit group (nible) of 4 bits. That is the reason they have been used and before also octal (3 bit per group) numbers.

Analogous example, not to spoil your learning experience:

numtoword = {'one':1, 'zero':0}

number = ('one','zero','one','zero')
print tuple(numtoword[n] for n in number)
print 'is in decimal', sum(bit * 2**power
                           for power, bit  in enumerate(numtoword[n]
                                                # powers from enumerate right to left
                                                # slice step -1
                                                for n in number[::-1]
                                                )
                           )

You can lookup each nibble (hex digit) and just join the values of them together as each nibble corresponds one to one to binary digit group (nible) of 4 bits. That is the reason they have been used and before also octal (3 bit per group) numbers.

Analogous example, not to spoil your learning experience:

numtoword = {'one':1, 'zero':0}

number = ('one','zero','one','zero')
print tuple(numtoword[n] for n in number)
print 'is in decimal', sum(bit * 2**power
                           for power, bit  in enumerate(numtoword[n]
                                                # powers from enumerate right to left
                                                # slice step -1
                                                for n in number[::-1]
                                                )
                           )

Ok correct me if I am wrong.

I think this is what's going on here:
numtoword is the dictionary
number could be the user input
you used the for loop to iterate over all values in numtoword using the user input.

Questions:
why did you write tuple()?
What is the: for power, bit loop for?

1) because tuple is fitting type for word sequence
2) just to show something for you to study later after you finish this program (notice that 1010b == 10 decimal)

As we know Python has ready methods to do this directly (bin, hex etc) but we are dealing programming exercises, when those ready things can only use mayby for testing purposes only.

Do not deal with user input yet leave it last. Just put fixed values in place of user input. First get the logic right.

We must not iterate all values of numtoword, we must iterate all values in input (a tuple in this case).

1) because tuple is fitting type for word sequence
2) just to show something for you to study later after you finish this program (notice that 1010b == 10 decimal)

As we know Python has ready methods to do this directly (bin, hex etc) but we are dealing programming exercises, when those ready things can only use mayby for testing purposes only.

Do not deal with user input yet leave it last. Just put fixed values in place of user input. First get the logic right.

We must not iterate all values of numtoword, we must iterate all values in input (a tuple in this case).

I found this table online to help me understand adding hexadecimal numbers:
http://www.saddleback.edu/faculty/lperez/algebra2go/tools/abacus/

basically I am trying to write a simpler/basic version of this in python.

1) because tuple is fitting type for word sequence
2) just to show something for you to study later after you finish this program (notice that 1010b == 10 decimal)

As we know Python has ready methods to do this directly (bin, hex etc) but we are dealing programming exercises, when those ready things can only use mayby for testing purposes only.

Do not deal with user input yet leave it last. Just put fixed values in place of user input. First get the logic right.

We must not iterate all values of numtoword, we must iterate all values in input (a tuple in this case).

I ran a modified version of your code to see how it played out, it worked, but it added the numbers individually.
This is what I got:
('0100, '1111', '1110', '1111')

I think what happened is that it went over each number and added it individually, instead of thinking of it as one large number.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.