gpt4 book ai didi

delphi - `bitpacked` 有关小端机问题的记录

转载 作者:行者123 更新时间:2023-12-02 14:33:30 25 4
gpt4 key购买 nike

我正在尝试在小端机器上使用FreePascal来读取和解释集成电路中的数据。数据本质上由紧密位封装(大部分)大端整数组成,其中一些(实际上很多)未与字节边界对齐。因此,我尝试使用 FPC 的 bitpacked 记录来实现此目的,但发现自己陷入了深深的麻烦。

我尝试读取的第一个结构具有以下格式:

{$BITPACKING ON}  
type
THeader = bitpacked record
Magic: Byte; // format id, 8 bits
_Type: $000..$FFF; // type specifier, 12 bits
Version: Word; // data revision, 16 bits
Flags: $0..$F // attributes, 4 bits
end;

这是一个阅读代码:

procedure TForm1.FormCreate(Sender: TObject);
var
F: File;
Header: THeader;
begin
Writeln(SizeOf(Header), #9, BitSizeOf(Header)); // reports correctly

Writeln('SizeOf(Header._Type) = ', SizeOf(Header._Type)); // correctly reports 2 bytes
Writeln('BitSizeOf(Header._Type) = ', BitSizeOf(Header._Type)); // correctly reports 12 bits

AssignFile(F, 'D:\3fd8.dat');
FileMode := fmOpenRead;
Reset(F, SizeOf(Byte));
BlockRead(F, Header, SizeOf(Header));

{ data is incorrect beyond this point already }

//Header._Type := BEtoN(Header._Type);

Writeln(IntToHex(Header.Magic, SizeOf(Header.Magic) * 2));
Writeln(IntToHex(BEtoN(Header._Type), SizeOf(Header._Type) * 2));
Writeln(BEtoN(Header.Version));
end;

但是代码打印的数据完全错误。

这是手动完成的数据和解释:

0000000000: F1 55 BE 3F 0A ...
Magic = F1
_Type = 55B
Version = E3F0
Flags = A

但 FPC 看待数据的方式截然不同且不正确。由于主机的小尾数,看起来属于字段的半字节(和位)不连续(例如:半字节 B 通常应属于 _Type 字段,而半字节 E - 到版本)。这是 Lazarus 的“ watch ”窗口:

enter image description here

请告诉我应该如何处理这种行为。这个非连续位域问题是 FPC 的错误吗?有什么可行的解决方法吗?

最佳答案

字节

F1 55 BE 3F 0A

具有以下连续半字节(低半字节在高半字节之前):

1 F 5 5 E B F 3 A 0

如果将它们分别分为 2、3、4 和 1 个半字节,您将得到:

 1 F     --> $F1    
5 5 E --> $E55 // highest nibble last, so E is highest.
B F 3 A --> $A3FB // same again: A is highest nibble
0 --> $0

这对应于您在“监视”窗口中看到的结果,而不是您手动解码的结果。

现在,如果数据是大尾数,那么您必须使用移位和掩码手动解码:

X.Magic := bytes[0];
X._Type := (bytes[1] shl 4) or (bytes[2] shr 4);
X.Version := ((bytes[2] and $0F) shl 12) or
(bytes[3] shl 4) or
(bytes[4] shr 4);
X.Flags := bytes[4] and $0F;

关于delphi - `bitpacked` 有关小端机问题的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31848246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com