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

Delphi 位元操作進階:從位元組提取到單一位元操作完整教學

     編輯:Delphi

Delphi 中 Integer 為 32 位元有號整數,但最小內建類型 Byte 為 8 位元。本文循序漸進示範如何從 32 位元整數中提取特定位元組、進而提取任意單一位元 (0-31),並深入解析位元遮罩與位移運算的核心原理。

基礎知識:位元組與位元

  • 1 Byte = 8 bits
  • Integer = 4 Bytes = 32 bits (位元編號 0-31,第 31 位為符號位)
  • 十六進位表示:每 2 字元 = 1 Byte (如 $7FFFFFFF = 0111 1111 1111 1111 1111 1111 1111 1111)

階段一:提取位元組 (Byte)

方法 A:內建函數 Lo/Hi

var
  i: Integer = $7FF00FFF;  // 0111 1111 1111 0000 0000 1111 1111
  b: Byte;
begin
  b := Lo(i);        // 低位元組 (Byte 0) = $FF
  b := Hi(i);        // 次低位元組 (Byte 1) = $0F
  b := Lo(i shr 16); // Byte 2 = $F0
  b := Hi(i shr 16); // Byte 3 = $7F
end;

方法 B:通用位元遮罩與位移 (核心技巧)

b := (i       and $FF);        // Byte 0
b := (i shr 8  and $FF);        // Byte 1
b := (i shr 16 and $FF);        // Byte 2
b := (i shr 24 and $FF);        // Byte 3

原理解析:$FF = 11111111 (二進位),AND 運算保留低 8 位,高位歸零。SHR n 右移 n 位將目標位元組移至最低位,再 AND $FF 擷取。

階段二:提取單一位元 (Bit)

同理,單一位元最大值為 1 (十六進位 $1):

var
  i: Integer = $7FF00FFF;  // 0111 1111 1111 0000 0000 1111 1111
  b: Byte;
begin
  { 第 0 位 (最低位) }
  b := i and 1;           // = 1
  b := i shr 0 and 1;     // 同義
  
  { 第 1 位 }
  b := i shr 1 and 1;     // = 1
  
  { 第 13 位 }
  b := i shr 13 and 1;    // = 0
  
  { 第 31 位 (符號位/最高位) }
  b := i shr 31 and 1;    // = 0 (正數)
end;

階段三:判斷正負數 (最高位檢測)

var
  i: Integer;
begin
  i := MaxInt;  // 2147483647 ($7FFFFFFF)
  if i shr 31 = 0 then ShowMessage('正數');  // 最高位 0
  
  i := -1;      // $FFFFFFFF (補碼全 1)
  if i shr 31 = 1 then ShowMessage('負數');  // 最高位 1
end;

核心原理深度解析

為什麼 x and $FF 能保留 0-255 的值?

0 and $FF = 0     (00000000 & 11111111 = 00000000)
1 and $FF = 1     (00000001 & 11111111 = 00000001)
100 and $FF = 100 (01100100 & 11111111 = 01100100)
255 and $FF = 255 (11111111 & 11111111 = 11111111)

任何 0-255 的數值,二進位最高不超過第 7 位,與 $FF (8 位全 1) AND 後完全保留原值。

Byte 類型的截斷特性

b := Byte(MaxInt);  // MaxInt = $7FFFFFFF,取低位元組 = $FF = 255

Byte 只佔 1 Byte,賦值超過 255 時自動截取低 8 位。

實務應用模式

  1. 旗標儲存:單一 Integer 可儲存 32 個 Boolean 旗標 (如視窗狀態、權限位)。
  2. 顏色拆解:R := Color and $FF; G := Color shr 8 and $FF; B := Color shr 16 and $FF;
  3. 網路協定封包:位元欄位解析 (如 TCP Flags: SYN=bit1, ACK=bit4...)。
  4. 高效能資料結構:位陣列、布隆過濾器、壓縮儲存。

常用輔助函數封裝建議

function GetBit(Value: Integer; Index: Integer): Boolean; inline;
begin
  Result := (Value shr Index) and 1 = 1;
end;

function GetByte(Value: Integer; Index: Integer): Byte; inline; // Index 0-3
begin
  Result := (Value shr (Index * 8)) and $FF;
end;

procedure SetBit(var Value: Integer; Index: Integer; On: Boolean); inline;
begin
  if On then Value := Value or (1 shl Index)
  else Value := Value and not (1 shl Index);
end;

效能提示

  • 位元運算 (and, or, xor, not, shl, shr) 為 CPU 單指令,極快。
  • 避免在緊迴圈中呼叫函數,使用 inline 或直接內聯代碼。
  • 64 位元整數 (Int64) 同理,支援 0-63 位。

熟練掌握位元遮罩與位移技巧,是進行底層優化、協定解析、硬體介面開發的必備基本功。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved