Skip to content Skip to sidebar Skip to footer

Writing A Function To Convert Hex To Decimal

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 h

Solution 1:

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

defhex_to_dex(strng_of_hex):
    returnint(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:

defhex(s):
    _hexer = "0123456789ABCDEF"returnsum([_hexer.find(var) * 16 ** i for i, var inenumerate(reversed(s.upper()))])

If you wanted to put some guards in:

defhex(s):
    _hexer = "0123456789ABCDEF"ifnotall([var in _hexer for var in s.upper()]):
        print"Invalid string"returnNonereturnsum([_hexer.find(var) * 16 ** i for i, var inenumerate(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.

Solution 2:

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.

Post a Comment for "Writing A Function To Convert Hex To Decimal"