[자료구조] 수학 - 진법 변환 with Python

COCOBALL·2023년 5월 17일
0

알고리즘

목록 보기
31/37
post-thumbnail

👉 n 진수 → 10 진수

python에서는 기본적으로 int()라는 내장 함수를 지원

# 아래와 같은 형식으로 사용하며 base에서 변환할 진법을 입력
int(string, base)

print(int('111', 2))
print(int('222', 3))
print(int('333', 4))
print(int('444', 5))
print(int('555', 6))
print(int('FFF', 16))

# 7
# 26
# 63
# 124
# 215
# 4095

int() 내장함수를 사용하지 않고 n진수를 10진수로 변환하는 다른 방법

def convert(n, base):
		decimal = 0
		for index, value in enumerate(str(n)[::-1]):
				decimal += (3**index)*int(value)
		return decimal
print(convert(21, 3))
  1. n진수의 순서를 반대로 만든다.
  2. n의 제곱 차수를 늘려가면서 값을 곱해준다.
  3. 누적한다.

👉 10진수 → 2, 8, 16 진수

2, 8, 16 진수는 bin(), oct(), hex() 파이썬 내장 함수를 지원

  • 결과는 모두 string
print(bin(10))
print(oct(10))
print(hex(10))

# Ob1010
# Oo12
# Oxa
# Ob: 2진수, Oo: 8진수, Ox: 16진수

# 앞의 진법 표시를 지우는 방법은 [2:]를 하면 가능
print(bin(10)[2:])
print(oct(10)[2:])
print(hex(10)[2:])

# 1010
# 12
# a

👉 10진수 → n진수

10진수를 n진수로 변환하는 방법 (2진수-16진수)

import string

# temp = 0123456789abcdefghijklmnopqrstuvwxyz
temp = string.digits+string.ascii_lowercase

def convert(num, base):
		q, r = divmod(num, base)
		if q == 0:
				return temp[r]
		else:
				return convert(q, base) + temp[r]

print(convert(10, 2))
print(convert(10, 2))
print(convert(10, 2))
print(convert(10, 2))

# 1010
# 101
# 22
# 20

👉 n진수 → n진수

import string

temp = string.digits+string.ascii_lowercase
def convert(num, base):
		q, r = divmod(num, base)
			if q == 0:
					return temp[r]
			else:
					return convert(q, base) + temp[r]

print(convert(int('a', 16), 2))
print(convert(int('4', 5), 3))
print(convert(int('2', 3), 4))
print(convert(int('11', 2), 5))

# 1010
# 11
# 2
# 3
profile
Welcome! This is cocoball world!

0개의 댓글