본문 바로가기
Python/문법

[Python] 파이썬 2진수, 8진수, 16진수 표현 및 변환 방법

by 에파 2024. 7. 19.
728x90

파이썬에서는 숫자를 2진수, 8진수, 16진수로 표현하고 변환할 수 있습니다. 각 진법에 대해 알아보고, 이를 표현하고 변환하는 방법에 대해서 알아보겠습니다. 게시글 하단에 진법 변환에 대해 요약을 해놓았습니다.

 

1. 2진수 (Binary)

2진수는 숫자 0과 1을 사용하여 수를 표현합니다. 파이썬에서는 'bin()' 함수를 사용하여 숫자를 2진수 문자열로 변환할 수 있고, 접두사 '0b'를 사용하여 2진수를 나타냅니다.

 

# 2진수로 변환
num = 10
binary_representation = bin(num)
print(binary_representation)  # Output: 0b1010

# 2진수 문자열을 정수로 변환
binary_str = "0b1010"
decimal_representation = int(binary_str, 2)
print(decimal_representation)  # Output: 10

 

이 때, 'int(binary_str, 2)' 라는 것은 binary_str 이라는 문자열을 2진수로 해석하여 10진수 정수로 변환하는 함수입니다.

 

2. 8진수 (Octal)

8진수는 숫자 0부터 7까지를 사용하여 수를 표현합니다. 파이썬에서는 'oct()' 함수를 사용하여 숫자를 8진수 문자열로 변환할 수 있으며, 접두사 '0o'를 사용하여 8진수를 나타냅니다.

 

# 8진수로 변환
num = 10
octal_representation = oct(num)
print(octal_representation)  # Output: 0o12

# 8진수 문자열을 정수로 변환
octal_str = "0o12"
decimal_representation = int(octal_str, 8)
print(decimal_representation)  # Output: 10

 

3. 16진수 (Hexadecimal)

16진수는 숫자 0부터 9와 문자 A부터 F (또는 a부터 f)를 사용하여 수를 표현합니다. 파이썬에서는 'hex()' 함수를 사용하여 숫자를 16진수 문자열로 변환할 수 있으며, 접두사 '0x' 를 사용하여 16진수를 나타냅니다.

 

# 16진수로 변환
num = 255
hexadecimal_representation = hex(num)
print(hexadecimal_representation)  # Output: 0xff

# 16진수 문자열을 정수로 변환
hexadecimal_str = "0xff"
decimal_representation = int(hexadecimal_str, 16)
print(decimal_representation)  # Output: 255

 

4. 진법 변환 요약

10진수를 다른 진법으로 변환

num = 42

binary = bin(num)    # 0b101010
octal = oct(num)     # 0o52
hexadecimal = hex(num)  # 0x2a

print(f"Binary: {binary}, Octal: {octal}, Hexadecimal: {hexadecimal}")
# Output: Binary: 0b101010, Octal: 0o52, Hexadecimal: 0x2a

 

다른 진법을 10진수로 변환

binary_str = "0b101010"
octal_str = "0o52"
hexadecimal_str = "0x2a"

decimal_from_binary = int(binary_str, 2)    # 42
decimal_from_octal = int(octal_str, 8)      # 42
decimal_from_hexadecimal = int(hexadecimal_str, 16)  # 42

print(f"From Binary: {decimal_from_binary}, From Octal: {decimal_from_octal}, From Hexadecimal: {decimal_from_hexadecimal}")
# Output: From Binary: 42, From Octal: 42, From Hexadecimal: 42

댓글