Hexadecimal output: Exercise 2.4
Hexadecimal numbers are fairly common in the world of computers. Actually, that’s not entirely true: some programmers use them all of the time. Other programmers, typically using high-level languages and doing things such as Web development, barely ever remember how to use them.
Now, the fact is that I barely use hexadecimal numbers in my day-to-day work. And even if I were to need them, I could use Python’s built-in hex function and 0x prefix. The former takes an integer and returns a hex string; the latter allows me to enter a number using hexadecimal notation, which can be more convenient. Thus, 0x50 is 80, and hex(80) will return the string 0x50.
For this exercise, you need to write a program that takes a hex number and returns the decimal equivalent. That is, if the user enters 50, then we will assume that it is a hex number (equal to 0x50), and will print the value 80 on the screen.
In [6]:
conversion_table = {
'A': 10,
'B': 11,
'C': 12,
'D': 13,
'E': 14,
'F': 15
}
def conver_hex_char_to_dec_num(hex_char):
_hex_char = hex_char.upper()
if '0' <= _hex_char <= '9':
dec = int(_hex_char)
elif 'A' <= _hex_char <= 'F':
dec = conversion_table[_hex_char]
else:
raise ValueError("invalid hex char {0}".format(hex_char))
return dec
In [8]:
def hex_to_dec(hex_str):
result = None
for hex_char in hex_str:
dec_num = conver_hex_char_to_dec_num(hex_char)
if result is None:
result = dec_num
else:
result = result * 16 + dec_num
return result
print hex_to_dec('ff')
In [16]:
[ord(_) for _ in '0123456789ABCDEFabcdef']
5 in range(4,10)
Out[16]:
In [ ]: