진법

Sooin Yoon·2025년 3월 17일

10진수 -> X진수 변환

ex) 10진수 8 -> 2진수 : 1000
10진수 17 -> 2진수 : 1001
10진수 25 -> 2진수 : 11001
10진수 8 -> 8진수 : 10
10진수 17 -> 8진수 : 21
10진수 25 -> 8진수 : 31

파이썬 코드

10진수 -> 2진수, 8진수, 16진수
binary : bin() print('2진수: {}'.format(bin(dNum))) == .format(dNum, '#b')
octal : oct() print('8진수: {}'.format(oct(dNum))) == .format(dNum, '#o')
Hexadecimal : hex() print('16진수: {}'.format(hex(dNum))) == .format(dNum, '#x')

변환결과는 다 문자열!
Type of bin(dNum): <class 'str'>
Type of oct(dNum): <class 'str'>
Type of hex(dNum): <class 'str'>

X진수 -> 10진수 변환

ex) 2진수 1000 -> 10진수 : 1 2^3 = 8
2진수 10001 -> 10진수 : 1
2^4 + 1 2^0 = 17
2진수 11000 -> 10진수 : 1
2^4 + 1 2^3 = 25
(.... 2^4, 2^3, 2^2, 2^1, 2^0)
8진수 10 -> 10진수 : 1
8^1 = 8
8진수 21-> 10진수 : 2 8^1 + 1 8^0 = 17
8진수 31 -> 10진수 : 3 8^1 + 1 8^0 = 25
(.... 8^2, 8^1, 8^0)

파이썬 코드

print('2진수(0b11110) -> 10진수({})'.format(int('0b11110', 2)))
print('8진수(0o36) -> 10진수({})'.format(int('0o36', 8))
print('16진수(0x1e) -> 10진수({})'.format(int('0x1e', 16))

2진수 -> 8진수 변환

뒤에서 부터 3자리씩 구분하고 빈 자리는 0으로 채움
ex) 2진수 1010100 -> 8진수 124
001 010 100
0 2^2 + 0 2^1 + 1 2^0 => 1
0
2^2 + 1 2^1 + 0 2^0 => 2
1 2^2 + 0 2^1 + 0 * 2^0 => 4

2진수 -> 16진수 변환

뒤에서부터 4자리씩 구분하고 빈 자리는 0으로 채움
ex) 2진수 1010100 -> 16진수 54
0101 0100
0 2^3 + 1 2^2 + 0 2^1 + 1 2^0 = 5
0 2^3 + 1 2^2 + 0 2^1 + 0 2^0 = 4

print('2진수(0b11110) -> 8진수({})'.format(oct(0b11110)))
print('2진수(0b11110) -> 10진수({})'.format(int(0b11110)))
print('2진수(0b11110) -> 16진수({})'.format(hex(0b11110)))

print('8진수(0o36) -> 2진수({})'.format(bin(0o36)))
print('8진수(0o36) -> 10진수({})'.format(int(0o36)))
print('8진수(0o36) -> 16진수({})'.format(hex(0o36)))

print('16진수(0x1e) -> 2진수({})'.format(bin(0x1e)))
print('16진수(0x1e) -> 8진수({})'.format(oct(0x1e)))
print('16진수(0x1e) -> 10진수({})'.format(int(0x1e)))

0개의 댓글