1

I have a piece of code from an exam paper that I'm doing for extra help.

The code I need help with:

def Denary(Hex):
    Result = ''
    ErrorFound = False
    DenaryEquivalent = ''
    EmptyInput=""
    for ThisHexDigit in Hex:
        if ThisHexDigit in ['1','2','3','4','5','6','7','8','9','0','A','B','C','D','E','F']:
            if ThisHexDigit == '0': DenaryEquivalent = '0'
            elif ThisHexDigit == '1': DenaryEquivalent = '1'
            elif ThisHexDigit == '2': DenaryEquivalent = '2'
            elif ThisHexDigit == '3': DenaryEquivalent = '3'
            elif ThisHexDigit == '4': DenaryEquivalent = '4'
            elif ThisHexDigit == '5': DenaryEquivalent = '5'
            elif ThisHexDigit == '6': DenaryEquivalent = '6'
            elif ThisHexDigit == '7': DenaryEquivalent = '7'
            elif ThisHexDigit == '8': DenaryEquivalent = '8'
            elif ThisHexDigit == '9': DenaryEquivalent = '9'
            elif ThisHexDigit == 'A': DenaryEquivalent = '10'
            elif ThisHexDigit == 'B': DenaryEquivalent = '11'
            elif ThisHexDigit == 'C': DenaryEquivalent = '12'
            elif ThisHexDigit == 'D': DenaryEquivalent = '13'
            elif ThisHexDigit == 'E': DenaryEquivalent = '14'
            elif ThisHexDigit == 'F': DenaryEquivalent = '15'
            elif ThisHexDigit == '10': DenaryEquivalent = '16'
            elif Hex==EmptyInput:
                print('Empty input, try again.')
            Result = Result + DenaryEquivalent
        else:
            ErrorFound == True
            print('You have made a mistake')

    def HexToDenary():
        Hexadecimal = input('Enter a hexadecimal number: ')
        Converted = Denary(Hexadecimal)
        print (Converted)

When run, there are no errors and the program works (this is only part of it). What I want to know is how I'd add the result instead of it appearing as a binary answer. For example if I enter 'BB', I get '1111' instead of 187. It should be easy but I can't figure it out.

And I know this is an over complicated piece of code but it is what was given.

18
  • 2
    I'm sorry, not getting this: hex BB is 187, not 22.
    – bereal
    Apr 13, 2012 at 12:37
  • 3
    You should not use elif ThisHexDigit == '10' as thisHexDigit will never have more than one character which means the elif part would never be executed.
    – cfedermann
    Apr 13, 2012 at 12:38
  • 8
    This code is what was given to you? By whom? I really hope it's not someone who is licensed to teach programming. Apr 13, 2012 at 12:40
  • 6
    Unbelievable. Which university? I don't think I have ever seen a worse Python program :) Apr 13, 2012 at 12:42
  • 3
    @user1331579 I apologise on behalf of the site. The code is really awful. Of course the blame lies with the examiner who wrote this code and you’re getting the brunt of the (justified) anger. Apr 13, 2012 at 13:50

3 Answers 3

3

The problem is your equivalents are strings, not integers, so they get concatenated, not added.

So to solve:

if ThisHexDigit == '0': DenaryEquivalent = 0

However, you are showing a really bad way of doing this. Naturally the best way would be to use Python's built in handling of different numerical bases (int(hex_string ,16)), however, presuming the aim of this is a programming exercise, Instead of using a lot of if statements, using a dict would be appropriate.

hex_digits_to_dec = {"0": 0, ..., "F": 15}

A quick way of producing this is as follows:

hex_digits_to_dec = {k: v for (v, k) in enumerate('0123456789ABCDEF')}

Enumerate returns tuples of (n, v) where v is each value from the iterable (in this case a string) you pass in, and n is a number, counting from 0. We use a dict comprehension to take this, reverse the key and value, and make a dictionary. You could just write this out by hand if you found it easier or clearer.

Then we can just do:

hex_string = hex_string.upper() #Save ourselves any errors from lowercase hex strings.
result = 0
try:
    for digit in hex_string:
        result = 16*result + hex_digits_to_dec[digit]
except KeyError:
    print("You made a mistake, this is not a valid hexadecimal number.")

This loops through our hex string, multiplying the previous values by 16 (as we go along, each digit is worth 16 times less than the digit to the left of it), and adding our new digit's value.

It is also worth noting that PEP-8 recommends CapWords for classes, and lowercase_with_underscores for local variables.

My old answer used this instead:

for power, digit in enumerate(reversed(hex_string)):
    result += (16**power)*hex_digits_to_dec[digit]

We reverse the string to get the lowest value digits first, then enumerate them to tell us the position (and therefore the value) of the digit. We take 16 to the power of this (to get the value of 1 at that position), and then multiply that by the value of the digit, and add them all together.

This works, but it was pointed out it's a less efficient method.

2
  • This will still give you 22 as a result, not 187 for the input BB. Apr 13, 2012 at 12:45
  • It seems better to write result = result * 16 + ... since ** may be expensive; also can optimize as result << 4. Also, enumerate('0123456789abcdef') looks better.
    – bereal
    Apr 13, 2012 at 13:05
2

You need to change 2 lines in your program

Result = ''

to

Result=0

and

Result = Result + DenaryEquivalent

to

Result = Result*16 + int(DenaryEquivalent)

Off course you can simplify it by using dictionary

>>> def denary(hex):
    denary_equivalent={'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,'10':16}
    result = 0
    for this_hex_digit in hex:
        if this_hex_digit in denary_equivalent:
            result=result*16+denary_equivalent[this_hex_digit]
    return result

>>> denary('BB')
187
>>> 
5
  • Thanks. It works to an extent that it adds, but BB gives 22 instead of 187 (made a mistake in the question) Apr 13, 2012 at 12:42
  • 1
    -1 - this is a terrible way of doing it. Why convert strings to ints when they can just be ints in the first place? Apr 13, 2012 at 12:43
  • @user1331579: See my update. You just need to multiply the result by 16 before adding the new value
    – Abhijit
    Apr 13, 2012 at 12:48
  • After you added the *16 it now works. BB gives 187. Thank-you. Apr 13, 2012 at 12:49
  • .keys() is unnecessary. if ThisHexDigit in DenaryEquivalent: already does just that. You should also rename the variables. Uppercase is by convention reserved for classes. Apr 13, 2012 at 12:51
-1

Your programme works with strings. + concatenates strings.

You need to convert your operands to numbers.

In addition, you should use a dict for mapping from one set of data to another:

dict((b,a) for a,b in enumerate(['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','10'])))

Note also that your programme doesn't perform the conversion correctly, because it doesn't raise each digit to the correct power.

2
  • This produces a Decimal: Hexadecimal dict, when what is needed is the other way around. See my answer. Apr 13, 2012 at 13:00
  • Yes, but the fundamental point is that it produces a dict, which I imagine the OP is not aware of.
    – Marcin
    Apr 13, 2012 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.