Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chuyển đổi nhị phân ↔ thập phân trong Python

Chuyển đổi giữa hệ nhị phân (base-2) và thập phân (base-10) thủ công và dùng built-in.

1. Thập phân → Nhị phân

Thuật toán: Chia liên tiếp cho 2, lấy phần dư đọc ngược.

def dec_to_bin(n):
    if n == 0: return "0"
    bits = []
    while n > 0:
        bits.append(str(n % 2))
        n //= 2
    return ''.join(reversed(bits))

print(dec_to_bin(15))  # 1111

# Built-in
print(bin(15))         # 0b1111
print(format(15, 'b')) # 1111

2. Nhị phân → Thập phân

Thuật toán: Σ bitᵢ × 2ⁱ (từ phải sang trái).

def bin_to_dec(binary_str):
    return sum(int(bit) * (2**i) for i, bit in enumerate(reversed(binary_str)))

print(bin_to_dec("1111"))  # 15

# Built-in
print(int("1111", 2))      # 15
print(int("0b1111", 0))    # 15 (auto-detect base)

3. Menu tương tác

print("1. Dec → Bin")
print("2. Bin → Dec")
choice = int(input("Chọn: "))

if choice == 1:
    n = int(input("Số thập phân: "))
    print(f"Nhị phân: {format(n, 'b')}")
elif choice == 2:
    b = input("Số nhị phân: ")
    print(f"Thập phân: {int(b, 2)}")

Mở rộng: Hệ cơ số bất kỳ

def convert_base(num, from_base, to_base):
    # Chuyển về thập phân trước
    decimal = int(str(num), from_base)
    # Chuyển từ thập phân sang to_base
    digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    if decimal == 0: return "0"
    result = ""
    while decimal > 0:
        result = digits[decimal % to_base] + result
        decimal //= to_base
    return result

print(convert_base("1111", 2, 16))  # F
print(convert_base("FF", 16, 8))    # 377