0
0

Pythonで進数変換

Posted at

はじめに

10進数 ⇔ n進数の変換手法についての記事です.

動作環境

  • Python 3.12.0
  • numpy 1.26.2

ソースコード

import numpy as np

def convert_to_nNumber(input_num, radix):
    cNum = np.base_repr(input_num, radix)
    return cNum

def convert_to_decimal_number(input_sNum, radix):
    cNum = int(input_sNum, radix)
    return cNum

# 10進数の100を16進数に変換
print(convert_to_nNumber(100, 16))
# 2進数"0b110"を10進数に変換
print(convert_to_decimal_number("110", 2))

解説

cNum = np.base_repr(input_num, radix)

10進数からn進数に変換する際は,numpyのbase_repr関数を使用します.
input_numには変換する数字を,radixには基数を設定します.

cNum = int(input_sNum, radix)

n進数から10進数に変換する際は,int関数を使用します.
input_sNumにはstr型でn進数表記の値を,radixにはinput_sNumの基数を設定します.

bin,oct,hex関数

10進数から2進数,8進数,16進数への変換は,binocthex関数を使用することでも可能です.

print(bin(10), oct(10), hex(10))
# Output -> 0b1010 0o12 0xa
0
0
0

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
0
0