はじめに
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進数への変換は,bin
,oct
,hex
関数を使用することでも可能です.
print(bin(10), oct(10), hex(10))
# Output -> 0b1010 0o12 0xa