//按单字节反转内存的函数
procedure ReverseMemory(P: PByte; Len: Integer); overload;
var
  B: Byte;
  P2: PByte;
begin
  P2 := P;
  Inc(P2, Len - 1);
  while Integer(P) < Integer(P2) do
  begin
    B := P^;
    P^ := P2^;
    P2^ := B;
    Inc(P);
    Dec(P2);
  end;
end;

//按双字节反转内存的函数
procedure ReverseMemory(P: PWord; Len: Integer); overload;
var
  W: Word;
  P2: PWord;
begin
  P2 := P;
  Inc(P2, Len div 2 - 1);
  while Integer(P) < Integer(P2) do
  begin
    W := P^;
    P^ := P2^;
    P2^ := W;
    Inc(P);
    Dec(P2);
  end;
end;

//按四字节反转内存的函数
procedure ReverseMemory(P: PInteger; Len: Integer); overload;
var
  I: Integer;
  P2: PInteger;
begin
  P2 := P;
  Inc(P2, Len div 4 - 1);
  while Integer(P) < Integer(P2) do
  begin
    I := P^;
    P^ := P2^;
    P2^ := I;
    Inc(P);
    Dec(P2);
  end;
end;

//调用测试
procedure TForm1.Button1Click(Sender: TObject);
var
  bs: TBytes;
  i: Integer;
begin
  SetLength(bs, 8);
  for i := 0 to Length(bs) - 1 do bs[i] := i + 49;
  ShowMessage(StringOf(bs)); {12345678}

  for i := 0 to Length(bs) - 1 do bs[i] := i + 49;
  ReverseMemory(PByte(bs), Length(bs));
  ShowMessage(StringOf(bs)); {87654321}

  for i := 0 to Length(bs) - 1 do bs[i] := i + 49;
  ReverseMemory(PWord(bs), Length(bs));
  ShowMessage(StringOf(bs)); {78563412}

  for i := 0 to Length(bs) - 1 do bs[i] := i + 49;
  ReverseMemory(PInteger(bs), Length(bs));
  ShowMessage(StringOf(bs)); {56781234}
end;

posted on 2009-11-12 16:49  万一  阅读(3121)  评论(9编辑  收藏  举报