[Delphi] 字节序交换函数

最佳性能版:

function Swap16(const Value: Word): Word; inline;
begin
  Result := Swap(Value);
end;

function Swap32(const Value: LongWord): LongWord; inline;
begin
  Result := Swap(Word(Value)) shl 16 + Swap(Word(Value shr 16));
end;

function Swap64(const Value: Int64): Int64;
{$IFDEF WIN32}
asm
  mov     edx, [ebp + $08]
  mov     eax, [ebp + $0c]
  bswap   edx
  bswap   eax
{$ELSE}
{$IFDEF WIN64}
asm
  mov     rax, rcx
  bswap   rax
{$ELSE}
begin
  Result := Swap32(LongWord(Value));
  Result := (Result shl 32) or Swap32(LongWord(Value shr 32));
{$ENDIF}
{$ENDIF}
end;

function SwapFloat(const Value: Single): Single; overload; inline;
var
  R: LongWord absolute Result;
  V: LongWord absolute Value;
begin
  R := Swap32(V);
end;

function SwapFloat(const Value: Double): Double; overload; inline;
var
  R: Int64 absolute Result;
  V: Int64 absolute Value;
begin
  R := Swap64(V);
end;

 

其它版本:

function ExchangeByteOrderDouble(const PV: PAnsiChar): Double;
var
  pd: PAnsiChar;
begin
  pd := @Result;
  pd[0] := pv[7];
  pd[1] := pv[6];
  pd[2] := pv[5];
  pd[3] := pv[4];
  pd[4] := pv[3];
  pd[5] := pv[2];
  pd[6] := pv[1];
  pd[7] := pv[0];
end;

 

好吧,这个最慢

function SwapByteOrder(const Value: Double): Double; overload;
var
  V: Int64 absolute Result;
  VV: Int64 absolute Value;
begin
  V :=
    ((((VV and $00000000000000ff) shl 56) or
    ((VV and $000000000000ff00) shl 40) or
    ((VV and $0000000000ff0000) shl 24) or
    ((VV and $00000000ff000000) shl 8) or
    ((VV and $000000ff00000000) shr 8) or
    ((VV and $0000ff0000000000) shr 24) or
    ((VV and $00ff000000000000) shr 40) or
    ((VV and $ff00000000000000) shr 56)));
end;

 

感谢 网友

@[合肥]全能地图 
 
posted @ 2016-08-12 22:48  我爱我家喵喵  阅读(1113)  评论(0编辑  收藏  举报