如何在 C 中获取与寄存器宽度无关的无符号整数变量?

发布于 2024-10-08 19:00:39 字数 411 浏览 3 评论 0原文

我正在为在 Intel x86 和 x64 架构(至少!)上运行的 Linux 编写代码,使用 gcc 转储和从内存读取数据结构到磁盘作为实现序列化的廉价方法。每个字段不应有额外的填充。

为此,我仔细组织了结构,以便每个字段具有存储信息所需的位数,并将它们手动对齐到 4 字节边界(应该是 8 个字节吗?)。

我开始研究大量的整数修改(intlong intlong long intunsigned long long int > 等),但没有找到关于此事的明确来源(通过虚拟程序获取有关结构的信息是无聊和乏味的,并且特定于我的硬件。)

这就是说,我需要一些字段为 16 位,一些字段为 32 位位和某些字段为 64 位。有办法实现这一点吗?

I'm writing code for Linux running on Intel x86 and x64 architectures (at least!) with gcc dumping and reading data structures from memory to disk as a cheap way to achieve serialization. Each field should have no padding additionally.

To do so I've carefully organized the structures so that each field has just as many bits as they need to store information and hand-aligned them to 4 bytes boundaries (should that be eight?).

I started looking at the plethora of integer modifications (int, long int, long long int, unsigned long long int, etc.) but found no definitive source on the matter (and getting information about structures via dummy programs is boring and tedious and specific to my hardware.)

This said, I need some fields to be 16 bits, some fields to be 32 bits and some fields to be 64 bits. Is there a way to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花落人断肠 2024-10-15 19:00:39

您可以使用 C99 标头 ,它定义了 int16_tuint32_t 等固定宽度类型。

显然,您仍然需要小心填充和对齐,但如果您确切知道每个数据成员有多大,那么这应该不会太困难。利用 GCC 的 < code>packed 和 aligned 属性以确保正确对齐。

You can use the C99 header <stdint.h>, which defines fixed-width types like int16_t and uint32_t, among many others.

You will still need to be careful with padding and alignment, obviously, but if you know exactly how large each data member is, it shouldn't be too difficult. It would still be beneficial for you to take advantage of GCC's packed and aligned attributes to ensure correct alignment.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文