I created a program to convert hexadecimal numbers to decimal numbers for learning python.
If you use the int function as shown below, you can convert it in one shot, so it is just learning.
main.py
print(int('3b',base=16))
terminal
59
The code actually created looks like the following.
main.py
base_num = '0123456789ABCDEF'
count_num = 3
def hex_to_int(hex_str):#Convert HEX string to number
i = len(hex_str)
value = 0
digits = 0
while i > 0:
value += base_num.find(hex_str[i - 1]) * (len(base_num) ** digits)
i -= 1
digits += 1
return value
if __name__ == "__main__":
num_list = []
while len(num_list) < count_num:
input_num = input('Please enter a hexadecimal number:')
input_num = input_num.upper()
#HEX string check
is_num_check = True
for num in input_num:
if not num in base_num:
is_num_check = False
if is_num_check:
input_val = hex_to_int(input_num)
num_list.append(input_val)
else:
print('Not a hexadecimal number')
print(*num_list)
Converts the entered hexadecimal number value to decimal number and returns it.
If you use the inclusion notation, you can write it shorter.
Recommended Posts