16進数を10進数に変換する

#!/usr/bin/python
## Converts hex to decimal
# Dictionary for hexadecimal. Covers both lower case and upper case.
hexDict = {'a':10, 'b':11, 'c':12, 'd':13, 'e':14, 'f':15, 'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15}
result = 0
# Get user input
myhex = raw_input('Enter hex: ')
# Reverse the input
myhex = myhex[::-1]
for i,j in enumerate(myhex):
# If the input contains "a-f(A-F)", convert to digits
if hexDict.get(j): # Use get() to avoid KeyError
digit = hexDict[j]
ans = int(digit) * (16 ** i)
else:
ans = int(j) * (16 ** i)
result += ans
print(result)

16進数を10進数に変換するスクリプトです。
変換の計算法については下記を参照。
http://www.asahi-net.or.jp/~ax2s-kmtn/ref/bdh.html

以上

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.