首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 用單個 Byte 存儲 8 個復選框狀態

     編輯:Delphi

原理

一個 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)翻轉

應用場景

  • 配置文件緊湊存儲多個開關選項。
  • 網絡協議標誌位字段編解碼。
  • 數據庫單字段存儲多個 Boolean 列,節省 Schema 變更。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved