Lazarus中如何将Integer转换为区分大小端的Byte数组?
在Lazarus中实现Integer与大/小端字节数组的转换
前提说明
Lazarus基于Free Pascal,默认Integer为32位(4字节)有符号整数,以下代码针对该类型实现转换,若需处理64位整数可替换为Int64并调整字节数。
小端(Little-endian)转换
x86/x86_64架构本身是小端模式,直接通过内存映射即可高效实现,无需额外字节排序:
function IntToBytesLE(const AValue: Integer): array[0..3] of Byte; begin // 直接将Integer的内存内容拷贝到字节数组 Move(AValue, Result, SizeOf(Integer)); end;
测试示例:当AValue = 1时,返回数组为 [01, 00, 00, 00],符合小端格式。
大端(Big-endian)转换
大端要求高位字节在前,需手动提取每个字节并按逆序排列:
function IntToBytesBE(const AValue: Integer): array[0..3] of Byte; begin Result[0] := Byte(AValue shr 24); // 最高位字节 Result[1] := Byte(AValue shr 16); Result[2] := Byte(AValue shr 8); Result[3] := Byte(AValue); // 最低位字节 end;
测试示例:当AValue = 1时,返回数组为 [00, 00, 00, 01],符合大端格式。
扩展说明
- 如果需要动态字节数组而非固定长度数组,可替换返回类型为
TBytes,通过SetLength分配内存后再完成拷贝/赋值。 - 若处理无符号整数,将
Integer替换为Cardinal即可,逻辑完全一致。
内容的提问来源于stack exchange,提问作者kerwin xu
相关产品推荐
相关产品推荐

