C 中表示 CPU 架构的 WORD 大小的原始数据类型
我观察到 long 的大小始终等于任何给定 CPU 架构的 WORD 大小。对于所有架构都是如此吗?我正在寻找一种可移植的方式来表示 C 中的 WORD 大小的变量。
I observed that size of long is always equal to the WORD size of any given CPU architecture. Is it true for all architectures? I am looking for a portable way to represent a WORD sized variable in C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
C 不处理指令。在 C99 中,您可以使用单个赋值来复制任何大小的 struct :
使用智能编译器,这应该生成最快的(单线程的,但将来希望是多线程的)代码来执行复制。
如果您想要供应商定义的“尽可能最快”的整数类型,则可以使用
int_fast8_t
类型。这可能与字长相对应,但当然不能保证单指令可写。我认为最好的选择是默认为一种类型(例如
int
)并使用 C 预处理器针对某些 CPU 进行优化。C doesn't deal with instructions. In C99, you can copy any size
struct
using an single assignment:With a smart compiler, this should generate the fastest (single-threaded, though in the future hopefully multi-threaded) code to perform the copy.
You can use the
int_fast8_t
type if you want the "fastest possible" integer type as defined by the vendor. This will likely correspond with the word size, but it's certainly not guaranteed to even be single-instruction-writable.I think your best option would be to default to one type (e.g.
int
) and use the C preprocessor to optimize for certain CPU's.不会。事实上,标量和向量单元通常具有不同的字长。然后还有字符串指令和具有奇怪功能的内置 DMA 控制器。
如果您想快速复制数据,平台标准 C 库中的
memcpy
通常是最快的。No. In fact, the scalar and vector units often have different word sizes. And then there are string instructions and built-in DMA controllers with oddball capabilities.
If you want to copy data fast,
memcpy
from the platform's standard C library is usually the fastest.在 Windows 下,
sizeof(long)
为 4,即使在 64 位版本的 Windows 上也是如此。Under Windows,
sizeof(long)
is 4, even on 64-bit versions of Windows.我认为您会得到的最接近的答案是...
int
和unsigned int
通常(但并非总是)与机器的寄存器宽度匹配。然而,架构通常并没有单一的字长 - 可以有不同宽度的寄存器(例如 Intel x86 中的“正常”寄存器与 MMX 寄存器),寄存器宽度通常与总线宽度不匹配,地址和数据可能有不同的宽度等等。
I think the nearest answers you'll get are...
int
andunsigned int
often (but not always) match the register width of the machine.intptr_t
and available from stddef.h IIRC. This should obviously match the address-width for your architecture, though I don't know that there's any guarantee.However, there often really isn't a single word-size for the architecture - there can be registers with different widths (e.g. the "normal" vs. MMX registers in Intel x86), the register width often doesn't match the bus width, addresses and data may be different widths and so on.
不,标准没有这种类型(具有最大化内存吞吐量)。
但它指出
int
必须是处理器执行 ALU 操作最快的类型。No, standard have no such type (with maximize memory throughput).
But it states that
int
must be fastest type for the processor for doing ALU operations on it.在嵌入式世界中事情会变得更加复杂。 ASAIK,C51 是 8 位处理器,但在 Keil C for c51 中,long 有 4 个字节。我认为这取决于编译器。
Things will get more complicated in embedded world. ASAIK, C51 is 8bit processor but in Keil C for c51, long have 4 bytes. I think it's compiler dependent.