Delphi 7实现UInt32转小端序十六进制字节序列
Delphi 7 实现 UInt32 转小端字节序列
要将数值104964转换为小端序字节序列04 9A 01 00,核心是遵循小端序低字节在前的规则,以下是两种可行的Delphi 7实现方案:
方案1:利用内存映射记录(高效简洁)
通过packed record直接映射UInt32的内存布局,Delphi 7在小端系统下的内存存储本身就是小端序,因此可以直接提取字节:
type TUInt32Bytes = packed record case Boolean of False: (Value: UInt32); True: (Bytes: array[0..3] of Byte); end; function UInt32ToLittleEndianBytes(const AValue: UInt32): array[0..3] of Byte; var UInt32Data: TUInt32Bytes; begin UInt32Data.Value := AValue; Result := UInt32Data.Bytes; end;
测试示例
var OutputBytes: array[0..3] of Byte; begin OutputBytes := UInt32ToLittleEndianBytes(104964); // 结果:OutputBytes[0] = $04, OutputBytes[1] = $9A, OutputBytes[2] = $01, OutputBytes[3] = $00 end;
方案2:手动位运算提取字节(直观易懂)
通过位掩码和位移操作,依次取出UInt32的每个字节并按小端序排列:
function UInt32ToLittleEndianBytes(const AValue: UInt32): array[0..3] of Byte; begin Result[0] := Byte(AValue and $000000FF); // 提取最低字节 Result[1] := Byte((AValue and $0000FF00) shr 8); // 提取次低字节 Result[2] := Byte((AValue and $00FF0000) shr 16); // 提取次高字节 Result[3] := Byte((AValue and $FF000000) shr 24); // 提取最高字节 end;
两种方案都能得到目标字节序列,方案1利用内存直接映射,执行效率更高;方案2通过显式位操作,更便于理解小端序的转换逻辑。
内容的提问来源于stack exchange,提问作者Вячеслав
相关产品推荐
相关产品推荐

