[Python] 진법 변환

Hye·2023년 2월 22일

1️⃣ n진수 → 10진수

int()

  • int(string, base)로 사용
    • string : 바꾸려는 숫자의 string 형태
    • base : 진법 (n)
  • 결과값 : string
>>>int('111',2)
7
>>>int('222',3)
36

2️⃣ 10진수 → 2, 8, 6진수

  • 결과값 : string
  • 앞의 진법 표시를 지우려면 뒤에 [2:] 붙이면 됨
    • 0b : 2진수
    • 0o : 8진수
    • 0x : 16진수

bin()

  • 10진수 → 2진수
>>>bin(10)
0b1010

>>>bin(10)[2:]
1010

oct()

  • 10진수 → 8진수
>>>oct(10)
0o12

>>>oct(10)[2:]
12

hex()

  • 10진수 → 6진수
>>>hex(10)
0xa

>>>hex(10)[2:]
a

3️⃣ 10진수 → n진수

  • 직접 코딩해야 함
def solution(num, n):
	if number == 0:
        return '0'
        
    NUMBERS = "0123456789ABCDEF"
    
    res = ""
    while number > 0:
        number, mod = divmod(number, n)
        res += NUMBERS[mod]
    return res[::-1]
profile
공부중 📚

0개의 댓글