Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การแปลงเลขฐานสอง (Binary) และเลขฐานสิบ (Decimal) ใน Python

กำหนดเลขฐานสิบและเลขฐานสอง งานคือแปลงฐานสิบเป็นฐานสอง และฐานสองเป็นฐานสิบ

อัลกอริทึม

Binary to Decimal (Bintodec)

  1. รับเลขฐานสองเข้ามา
  2. หาความยาวของเลขฐานสอง
  3. ใช้ for loop แปลง: เช่น 1111 = 1×2³ + 1×2² + 1×2¹ + 1×2⁰ = 15
  4. แสดงผล

Decimal to Binary (Dectobin)

  1. รับเลขฐานสิบเข้ามา
  2. ใช้ while loop: หาร 2 เก็บเศษและผลหาร ตัวแปรคูณ 10 สะสมผลลัพธ์
  3. เศษแรกคือหลักสุดท้าย
  4. แสดงผล

โค้ดตัวอย่าง: เมนูเลือกโหมด


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:
    # Decimal to Binary
    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:
    # Binary to Decimal
    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)

print("******************************************************")

ผลลัพธ์ตัวอย่าง


Enter your choice: 1
Enter decimal to be converted: 15
The binary of the given number is 1111

Enter your choice: 2
Enter binary to be converted: 1111
The decimal of the given binary is 15

วิธีง่ายกว่า (Built-in Functions)


# Decimal to Binary
num = 15
print(bin(num))        # '0b1111'
print(bin(num)[2:])    # '1111' (ตัด 0b ออก)
print(format(num, 'b')) # '1111'

# Binary to Decimal
bin_str = '1111'
print(int(bin_str, 2))  # 15

# รองรับฐานอื่นๆ
print(int('FF', 16))    # 255 (Hex)
print(int('77', 8))     # 63 (Octal)
print(oct(63))          # '0o77'
print(hex(255))         # '0xff'

สรุป: สำหรับการใช้งานจริง ควรใช้ built-in functions bin(), int(x, base), format() ซึ่งเร็ว กระชับ และน้อยบั๊กกว่า