파이썬에선 숫자를 다른 n진수로 표현하는 방법이 여러가지가 있다.
참고로 n진수로 표현된 숫자 앞에 오는 0b, 0o, 0x는 차례대로 2, 8, 16진수를 나타낸다. 접두어가 빠지면 직접 비교가 불가능하다.
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() - 2진수 / oct() - 8진수 / hex() - 16진수 로 변환할 때 사용되며 문자열의 형태는 변환할 수 없다.
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'
format(숫자, '#b') 와 같은 형태로 변환이 가능하다. #b - 2진수 / #o - 8진수 / #x - 16진수로 #을 빼면 접두어 생략이 가능하다.
마찬가지로 문자열 형태는 변환할 수 없다.
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를 이용하여 첫 번째 인자로 진수를 넣고 두 번째 인자로는 몇 진수인지 명시해주면된다. 참고로 접두어를 생략해줘도 되며 문자열 형태로 되어있어야 변환이 가능하다.
프로그래머스의 '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
위와 같은 방식으로 다른 진법으로 나타낼 수 있다.