奇偶校驗位(Parity Check Bit) 產生器
在數位通訊中,奇偶校驗是最基礎的錯誤偵測方法。它可以分為:
偶校驗 (Even Parity):使包含校驗位在內的
1的總個數為偶數。奇校驗 (Odd Parity):使包含校驗位在內的
1的總個數為奇數。
import tkinter as tk
from tkinter import messagebox
class ParityGeneratorApp:
def __init__(self, root):
self.root = root
self.root.title("8-bit 奇偶校驗產生器")
self.root.geometry("400x350")
self.root.configure(padx=20, pady=20)
self.create_widgets()
def create_widgets(self):
# 輸入區
tk.Label(self.root, text="請輸入 8-bit 二進制序列:", font=("Arial", 10, "bold")).pack(anchor=tk.W)
self.ent_bits = tk.Entry(self.root, font=("Courier New", 14), width=15, justify='center')
self.ent_bits.insert(0, "10110010")
self.ent_bits.pack(pady=10)
# 按鈕區
btn_frame = tk.Frame(self.root)
btn_frame.pack(pady=10)
tk.Button(btn_frame, text="計算校驗位", command=self.calculate_parity,
bg="#4CAF50", fg="white", font=("Arial", 10, "bold"), padx=10).pack()
# 結果顯示區
self.result_frame = tk.LabelFrame(self.root, text=" 計算結果 ", padx=15, pady=15)
self.result_frame.pack(fill=tk.X, pady=20)
self.lbl_count = tk.Label(self.result_frame, text="1 的個數: -")
self.lbl_count.pack(anchor=tk.W)
self.lbl_even = tk.Label(self.result_frame, text="偶校驗位 (Even): -", font=("Arial", 10, "bold"), fg="blue")
self.lbl_even.pack(anchor=tk.W)
self.lbl_odd = tk.Label(self.result_frame, text="奇校驗位 (Odd): -", font=("Arial", 10, "bold"), fg="red")
self.lbl_odd.pack(anchor=tk.W)
self.lbl_final = tk.Label(self.result_frame, text="完整框架: -", wraplength=300)
self.lbl_final.pack(anchor=tk.W, pady=(10, 0))
def calculate_parity(self):
bit_str = self.ent_bits.get().replace(" ", "")
# 驗證輸入是否為 8 位元二進制
if len(bit_str) != 8 or not all(b in '01' for b in bit_str):
messagebox.showerror("輸入錯誤", "請確保輸入剛好 8 個 0 或 1")
return
# 計算 1 的數量
ones_count = bit_str.count('1')
# 偶校驗 (Even Parity): 如果 1 的個數是奇數,校驗位為 1;否則為 0
even_bit = 1 if ones_count % 2 != 0 else 0
# 奇校驗 (Odd Parity): 如果 1 的個數是偶數,校驗位為 1;否則為 0
odd_bit = 1 if ones_count % 2 == 0 else 0
# 更新 UI
self.lbl_count.config(text=f"1 的個數: {ones_count}")
self.lbl_even.config(text=f"偶校驗位 (Even): {even_bit}")
self.lbl_odd.config(text=f"奇校驗位 (Odd): {odd_bit}")
# 顯示加上偶校驗後的 9-bit 結果
self.lbl_final.config(text=f"完整框架 (加偶校驗): {bit_str} | {even_bit}")
if __name__ == "__main__":
root = tk.Tk()
app = ParityGeneratorApp(root)
root.mainloop()

沒有留言:
張貼留言