[Delphi] 字节序交换函数

本文提供了多种字节交换函数的实现方式,包括最佳性能版本及适用于不同数据类型的函数,如Word、LongWord、Int64、Single和Double等。同时对比了不同方法的效率,并给出了直接操作内存的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最佳性能版:

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;

 

感谢 网友

@[合肥]全能地图 
 

转载于:https://www.cnblogs.com/yangyxd/articles/5766850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值