1

I need to write a function that converts hex to decimal and I've got an idea of how to do it but I'm stuck at the first bit. So far I am taking the user input and returning it in hex, but this only works if I enter 1 thing at a time. The code is:

def hex(x):
    if x == "0":
        return 0
    elif x == "1":
        return 1
    elif x == "2":
        return 2
    elif x == "3":
        return 3
    elif x == "4":
        return 4    
    elif x == "5":
        return 5
    elif x == "6":
        return 6
    elif x == "7":
        return 7
    elif x == "8":
        return 8
    elif x == "9":
        return 9
    elif x == "A":
        return 10
    elif x == "B":
        return 11
    elif x == "C":
        return 12
    elif x == "D":
        return 13
    elif x == "E":
        return 14
    elif x == "F":
        return 15

print hex(raw_input().upper())

It works if I enter, for example, C then it returns 12, but if I enter 8C then it doesn't work. I can't figure out why this is.

JaAnTr
  • 896
  • 3
  • 16
  • 28
  • 1
    If `x` is equal to the string `8C`, which branch of your big `if ... elif` statement do you think will be taken? If you can answer that then you will have figured out why your code doesn't work. – Steve Jessop Oct 26 '13 at 10:15
  • You need to call your `hex()` function for _each character in the user input_; and then collect and print the result. – Burhan Khalid Oct 26 '13 at 10:45

2 Answers2

5

You can use int to make this a lot easier. Function:

def hex_to_dex(strng_of_hex):
    return int(strng_of_hex, 16)

Example:

>>> int("0xff", 16)
255

It does not matter if you have a 0x infront for int, it will ignore 0x in the string. So, the following will also work:

>>> int("a", 16)
10

As for a raw hex code from scratch, try the following:

def hex(s):
    _hexer = "0123456789ABCDEF"
    return sum([_hexer.find(var) * 16 ** i for i, var in enumerate(reversed(s.upper()))])

If you wanted to put some guards in:

def hex(s):
    _hexer = "0123456789ABCDEF"

    if not all([var in _hexer for var in s.upper()]):
        print "Invalid string"
        return None

    return sum([_hexer.find(var) * 16 ** i for i, var in enumerate(reversed(s.upper()))])

I've used a lot of functions here, but for quick reference, here's an appendix:

  1. str.find
  2. enumerate
  3. reversed -> reverses the string
  4. sum

As for the [...], its a list comprehension, you can find loads of resources on that.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
0

Currently you are passing the entire string the user inputs to your hex function. Because of this it works for 'C' but not for '8C'. You aren't checking for '8C' in your if statements. Therefor your hex function returns with the value None. In order to prevent this you need to pass the user inputted string to your hex function one character at a time.

assuming:

values = raw_input().upper()

and using your hex() function as defined in your question. you could:

print([hex(v) for v in values])

or if you don't want a list:

print(' '.join([str(hex(v)) for v in values]))

This uses the function you defined but applies it to all characters the user inputs... instead of just the first one.

This answer works under the assumption that you are happy with the current functionality and return types of your defined hex() function.

RMcG
  • 1,045
  • 7
  • 14
  • "but if I enter 8C then it doesn't work." I'm showing an explanation for this. He is apparently happy with the existing functionality "It works if I enter, for example, C" – RMcG Oct 26 '13 at 10:21
  • this uses his defined hex() the one in the question. – RMcG Oct 26 '13 at 10:22
  • Ah, then it's still a problem because `hex()` returns integers. Turning that into strings is not going to produce the desired output; `C8` will result in `128`, not `200`. – Martijn Pieters Oct 26 '13 at 10:24
  • @RMcG: ah, I see, sorry. I thought you were proposing a *replacement* for the questioner's `hex` function! – Steve Jessop Oct 26 '13 at 10:24
  • @SteveJessop No problem, I should have made it more apparent. – RMcG Oct 26 '13 at 10:33
  • @Martinjn The defined hex function returns integers and string, converting the string 'C' and integer 8 into a string will results in "C8". – RMcG Oct 26 '13 at 10:35