[Python-Basic]n進数に変換


Pythonでは、異なるn進数で数字を表す方法がたくさんあります.
なお、n進数で表される数字の前の0 b、0 o、0 xは、2、8、16進数の順で表される.接頭辞なしでは直接比較できません.

1. bin(), oct(), hex()

n = 29
print(bin(n)) # 0b11101
print(oct(n)) # 0o35
print(hex(n)) # 0x1d

print(29 == 0b11101) # True

n = '10'
print(bin(n)) # TypeError: 'str' object cannot be interpreted as an integer
bin()-バイナリ/oct()-8進数/16進数を16進数に変換し、文字列の形式を変換できません.

2. format()

n = 29
print(format(n, '#b')) # 0b11101
print(format(n, '#o')) # 0o35
print(format(n, '#x')) # 0x1d
print(format(n, '#X')) # 0X1D

print(format(n, 'b')) # 11101
print(format(n, 'o')) # 35
print(format(n, 'x')) # 1d

n = '29'
print(format(n, '#b')) # ValueError: Unknown format code 'b' for object of type 'str'
フォーマット(数値、「#b」)に変換できます.プレフィックスは、b-バイナリ/#o-8進数/#x-16進数から#を減算することで省略できます.
同様に、文字列形式は変換できません.

3.10進数に変換

print(int('0b11101', 2)) # 29
print(int('0o35', 8)) # 29
print(int('0x1d', 16) # 29

print(int('11101', 2)) # 29
print(int('35', 8)) # 29
print(int('1d', 16)) # 29

print(int(11101, 2)) # SyntaxError: unexpected EOF while parsing
intを用いて1番目のパラメータを整数,2番目のパラメータを整数と表す.参照として、接頭辞は省略できますが、文字列形式でのみ変換できます.

4.関数の作成と変換


これはプログラマーの「3進法反転」の問題を解くことで知られる方法です.
n = 15
tenary=''

while n > 0:
    n, mod = divmod(n, 3) # 3진법
    tenary = str(mod) + tenary
        
print(tenary) # 120
print(int(tenary, 3)) # 15
上記のように異なる陣法で表すことができる.