一個 Byte (8 位) 可對應 8 個布爾值。第 i 個復選框對應 Bit i (0-7)。設置/讀取位運算即可實現壓縮存儲。
var
num: Integer; // 實際只用低 8 位
procedure TForm1.FormCreate(Sender: TObject);
begin
Edit1.Text := '輸入一個 Byte 數';
CheckListBox1.Align := alLeft;
CheckListBox1.Items.CommaText := 'A,B,C,D,E,F,G,H';
end;
{ 從數值恢復勾選狀態 }
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
num := Lo(StrToIntDef(Edit1.Text, 0)); // 取低 8 位
Edit1.Text := IntToStr(num);
for i := 0 to 7 do
CheckListBox1.Checked[i] := (1 shl i) and num <> 0;
Caption := IntToStr(num);
end;
{ 從勾選狀態生成數值 }
procedure TForm1.CheckListBox1Click(Sender: TObject);
var
i: Integer;
begin
num := 0;
for i := 0 to 7 do
if CheckListBox1.Checked[i] then
num := num or (1 shl i);
Caption := IntToStr(num);
Edit1.Text := IntToStr(num);
end;
| 操作 | 代碼 | 說明 |
|---|---|---|
| 設置第 i 位 | num := num or (1 shl i) | 置 1 |
| 清除第 i 位 | num := num and not (1 shl i) | 置 0 |
| 讀取第 i 位 | (num and (1 shl i)) <> 0 | 返回 Boolean |
| 切換第 i 位 | num := num xor (1 shl i) | 翻轉 |