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

โปรแกรม Python แปลงรหัสเกรย์ (Gray Code) เป็นรหัสไบนารี


เมื่อต้องการแปลงรหัสเกรย์กลับเป็นรหัสไบนารี สามารถใช้วิธีการตรวจสอบบิตแต่ละตำแหน่งและสลับค่าตามกฎของ Gray Code

ตัวอย่างโค้ด

def flip_bit(bit):
    return '1' if bit == '0' else '0'

def gray_to_binary(gray):
    binary = ''
    binary += gray[0]
    for i in range(1, len(gray)):
        if gray[i] == '0':
            binary += binary[i - 1]
        else:
            binary += flip_bit(binary[i - 1])
    return binary

gray_code = "01101001"
print("The gray code is:")
print(gray_code)
print("Binary code of", gray_code, "is", gray_to_binary(gray_code))

ผลลัพธ์

The gray code is: 01101001
Binary code of 01101001 is 01001110

คำอธิบาย

  • ฟังก์ชัน flip_bit สลับค่า '0' เป็น '1' และในทางกลับกัน

  • ฟังก์ชัน gray_to_binary เริ่มจากบิตแรก (MSB) คงค่าเดิม

  • สำหรับบิตถัดไป: ถ้าบิต Gray เป็น '0' ให้คัดลอกบิตไบนารีก่อนหน้า ถ้าเป็น '1' ให้สลับค่า

  • สร้างสตริงไบนารีทีละตัวอักษรและคืนค่าผลลัพธ์