Delphi 中 Integer 為 32 位元有號整數,但最小內建類型 Byte 為 8 位元。本文循序漸進示範如何從 32 位元整數中提取特定位元組、進而提取任意單一位元 (0-31),並深入解析位元遮罩與位移運算的核心原理。
$7FFFFFFF = 0111 1111 1111 1111 1111 1111 1111 1111)Lo/Hivar
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 := (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 擷取。
同理,單一位元最大值為 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 位。
Integer 可儲存 32 個 Boolean 旗標 (如視窗狀態、權限位)。R := Color and $FF; G := Color shr 8 and $FF; B := Color shr 16 and $FF;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 或直接內聯代碼。Int64) 同理,支援 0-63 位。熟練掌握位元遮罩與位移技巧,是進行底層優化、協定解析、硬體介面開發的必備基本功。