1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonで16進数を10進数に変換するプログラムを作成してみた

Posted at

pythonの学習のため16進数を10進数に変換するプログラムを作成してみました。

下記のようにint関数を使えば一発で変換できるので、あくまでも学習です。

main.py
print(int('3b',base=16))
terminal
59

実際に作成したコードは下記の感じです。

main.py
base_num = '0123456789ABCDEF'
count_num = 3
def hex_to_int(hex_str):# HEX文字列を数値へ変換
    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('16進数を入力してください:')
        input_num = input_num.upper()

        # HEX文字列チェック
        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('16進数ではありません')

    print(*num_list)

入力した16進数の値を10進数に変換して返します。

内包表記を使えばもっと短く書けそうです。

1
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?