Problem: Convert the given hexadecimal string into decimal.
Example:
hex_to_decimal('198F')
6543
hex_to_decimal('19AF')
6575
Solution in Python:
def hex_to_decimal(hex_str):
"""
Author: Mayur P Srivastava
"""
"""
Author: Mayur P Srivastava
"""
decimal_number = 0
n = len(hex_str)
for i in range(n - 1, -1, -1):
c = ord(hex_str[i])
if c >= 65 and c <= 70:
c = 10 + c - 65
elif c >= 97 and c <= 102:
c = 10 + c - 97
elif c >= 48 and c <= 57:
c = c - 48
else:
assert False
decimal_number += 16**(n-i-1) * c
return decimal_number
Concepts Learned: Single loop, number system.
No comments:
Post a Comment