一个字节有8个bit,一般最高位是0
7 6 5 4 3 2 1 0
0 1a 1b 1c 1d 1e 1f 1g
要求把第二个字节的最低位放到第一个字节的最高位
7 6 5 4 3 2 1 0
2g 1a 1b 1c 1d 1e 1f 1g
0 0 2a 2b 2c 2d 2e 2f
以此类推,也就是说8个字节可以压缩成7个字节
7 6 5 4 3 2 1 0
0 1a 1b 1c 1d 1e 1f 1g
要求把第二个字节的最低位放到第一个字节的最高位
7 6 5 4 3 2 1 0
2g 1a 1b 1c 1d 1e 1f 1g
0 0 2a 2b 2c 2d 2e 2f
以此类推,也就是说8个字节可以压缩成7个字节
SysUtils;type
InBuffer = array [0..7] of byte;
OutBuffer = array [0..6] of byte;procedure Compact(I : InBuffer; var O : OutBuffer);
var
iLoop : Integer;
Mask : Byte;
begin
Mask := $01;
for iLoop := 0 to 6 do
begin
O[iLoop] := (I[iLoop] and $7F shr iLoop) + I[iLoop + 1] and Mask shl (7 - iLoop);
Mask := Mask shl 1 + 1;
end;
end;procedure Incompact(O : OutBuffer; var I : InBuffer);
var
iLoop : Integer;
Mask : Byte;
Low : Byte;
begin
Mask := $7F;
for iLoop := 0 to 7 do
begin
if iLoop > 0 then
Low := O[iLoop - 1] shr (8 - iLoop)
else
Low := 0;
I[iLoop] := Low + O[iLoop] and Mask shl iLoop;
Mask := Mask shr 1;
end;
end;var
I : InBuffer;
O : OutBuffer;
iLoop : Integer;
begin
I[0] := 1;
I[1] := 2;
I[2] := 3;
I[3] := 4;
I[4] := 5;
I[5] := 6;
I[6] := 7;
I[7] := 8;
Write ('Source = ');
for iLoop := 0 to 7 do Write (I[iLoop], ' ');
Writeln; Compact(I, O);
Write ('Compact = ');
for iLoop := 0 to 6 do Write (O[iLoop], ' ');
Writeln; Incompact(O, I);
Write ('Incompact = ');
for iLoop := 0 to 7 do Write (I[iLoop], ' ');
Writeln;
end.