Python/이론, 기초

[Python] 진수 변환

파송송 2022. 9. 28. 17:45
728x90

파이썬 진수

  • 파이썬은 기본으로 10진수를 사용함
    • 2진수 : 접두어 0b
    • 8진수 : 접두어 0o
    • 16진수 : 접두어 0x

내장함수

  • 파이썬에서 제공해주는 진수 변환 내장함수가 있음
  • 구분 접두사가 있어 str 자료형을 가지고 있음 
    • 2진수 : bin(num)
    • 8진수 : oct(num)
    • 16진수 : hex(num)
num = 13

b = bin(num)
o = oct(num)
h = hex(num)

print(b, o, h, sep = '\n')
print(type(b), type(o), type(h), sep = '\n')
0b1101
0o15
0xd
<class 'str'>
<class 'str'>
<class 'str'>

format() 진수 변환

  • format() 에서도 진수 변환이 가능함
num = 13

b = format(num, '#b')
o = format(num, '#o')
h = format(num, '#x')

print(b, o, h, sep = '\n')
print(type(b), type(o), type(h), sep = '\n')
0b1101
0o15
0xd
<class 'str'>
<class 'str'>
<class 'str'>

10진수로 변환하기

  • int( str, 진수) 로 str 타입으로 넣어야 함
  • return 값은 str 타입으로 받음
b_to_dec = int('0b1101', 2)
o_to_dec = int('0o15', 8)
h_to_dec = int('0xd', 16)

print(b_to_dec, o_to_dec, h_to_dec, sep='\n')
print(type(b), type(o), type(h), sep = '\n')
13
13
13
<class 'str'>
<class 'str'>
<class 'str'>

N진수로 변환하기

  • n진수에서 2진수로 변경할때 bin을 사용함
  • 이때 b는 int타입임
b = 0b1101

o = oct(b)
h = hex(b)
s = str(b)

print(o, h, s, sep='\n')
print(type(o), type(h), type(s), sep = '\n')
0o15
0xd
13
<class 'str'>
<class 'str'>
<class 'str'>

format N진수 변환

s = "2진수 : {0:b}, 8진수 : {0:o}, 10진수 : {0:x}, 16진수 : {0:x}".format(13)
print(s)
2진수 : 1101, 8진수 : 15, 10진수 : d, 16진수 : d
728x90