Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python으로 2진수·10진수 상호 변환하기: 알고리즘부터 예제 코드까지


주어진 10진수와 2진수를 서로 변환하는 것은 프로그래밍 학습에서 자주 만나는 기본 주제입니다. 이 글에서는 Python을 사용해 10진수 → 2진수, 그리고 2진수 → 10진수로 변환하는 방법을 알고리즘 단계, 예제 코드, 실행 결과까지 차근차근 살펴보겠습니다.

알고리즘

BinToDec() : 2진수를 10진수로 변환

Step 1: 2진수를 입력받습니다.
Step 2: 입력받은 2진수의 길이(자릿수)를 구합니다.
Step 3: for 반복문을 사용해 2진수를 10진수로 변환합니다.
예를 들어 2진수가 1111이라면 계산 과정은 다음과 같습니다.
1*2**3 + 1*2**2 + 1*2**1 + 1*2**0 = 15
Step 4: 결과값을 화면에 표시합니다.

DecToBin() : 10진수를 2진수로 변환

Step 1: 10진수를 입력받습니다.
Step 2: while 반복문을 사용합니다.
* 수를 2로 나누어 몫과 나머지를 구합니다. 초기값이 1인 별도의 변수를 하나 준비합니다.
나머지에 이 변수를 곱한 뒤 최종 출력값에 더하고, 이 변수는 반복할 때마다 10배씩 증가시킵니다.
* 첫 번째 나머지가 결과 값의 마지막 자릿수가 됩니다.
Step 3: 결과값을 화면에 표시합니다.

예제 코드

print("*****************************************************")
print(" DECIMAL TO BINARY AND BINARY TO DECIMAL CONVERSION")
print("*****************************************************")
print(" For Decimal to Binary...Press 1.")
print(" For Binary to Decimal... Press 2")
print("*****************************************************")

my_choice = int(input("Enter your choice: "))

if my_choice == 1:
    # 10진수 → 2진수 변환
    i = 1
    s = 0
    my_dec = int(input("Enter decimal to be converted: "))
    while my_dec > 0:
        rem = int(my_dec % 2)      # 나머지 구하기
        s = s + (i * rem)          # 자릿수에 맞춰 누적
        my_dec = int(my_dec / 2)   # 몫으로 갱신
        i = i * 10                 # 자릿수 이동
    print("The binary of the given number is ", s, '.')
else:
    # 2진수 → 10진수 변환
    my_bin = input('Enter binary to be converted: ')
    n = len(my_bin)
    res = 0
    for i in range(1, n + 1):
        res = res + int(my_bin[i - 1]) * 2 ** (n - i)
    print("The decimal of the given binary is ", res, '.')

실행 결과

① 10진수 → 2진수 변환

*****************************************************
DECIMAL TO BINARY AND BINARY TO DECIMAL CONVERSION
*****************************************************
For Decimal to Binary...Press 1.
For Binary to Decimal... Press 2
*****************************************************
Enter your choice: 1
Enter decimal to be converted: 15
The binary of the given number is 1111.
******************************************************

② 2진수 → 10진수 변환

*****************************************************
DECIMAL TO BINARY AND BINARY TO DECIMAL CONVERSION
*****************************************************
For Decimal to Binary...Press 1.
For Binary to Decimal... Press 2
*****************************************************
Enter your choice: 2
Enter binary to be converted: 1111
The decimal of the given binary is 15.
******************************************************

보너스: 내장 함수로 한 줄로 변환하기

직접 알고리즘을 구현하지 않더라도 Python의 내장 함수를 활용하면 훨씬 간단하게 변환할 수 있습니다.

# 10진수 → 2진수
print(bin(15))          # 0b1111
print(bin(15)[2:])      # 1111 ('0b' 접두사 제거)

# 2진수 → 10진수
print(int('1111', 2))   # 15

bin() 함수는 정수를 '0b' 접두사가 붙은 2진수 문자열로 반환하며, int() 함수는 두 번째 인자로 진법을 지정해 문자열을 해당 진법의 정수로 변환합니다. 실무에서는 이처럼 내장 함수를 사용하는 것이 가장 간결하고 오류 가능성이 낮은 방법입니다.