1
1

More than 1 year has passed since last update.

Pythonで10進数→N進数変換とN進数→10進数変換

Last updated at Posted at 2021-09-26

N進数から10進数への変換

int()関数の第2引数に指定した基数から10進数に変換してくれる

print(int('100', 2)) # 4
print(int('100', 3)) # 9

2つ目の引数には2〜36までの値を指定しないとエラーとなる

10進数からN進数への変換

2進数、8進数、16進数への変換

base10 = 10
print(format(base10, 'b')) # 1010
print(format(base10, 'o')) # 12
print(format(base10, 'x')) # a
print(type(format(base10, 'b'))) # <class 'str'>

変換後の型は文字列型である
2進数はbinaryの略でb
8進数はoctalの略でo
16進数はhexadecimalの略でx

2進数、8進数、16進数以外への変換

numpyをimportしてbase_repr関数を使うと良い

import numpy as np

print(np.base_repr(10, 7)) # 13
print(np.base_repr(13, 15)) # D
print(np.base_repr(-130, 20)) # -6A
print(np.base_repr(100, 36)) # 2S
1
1
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
1