gcc中的位域字节序 [英] Bitfield endianness in gcc
问题描述
位域的字节序由实现定义。有没有一种方法可以在编译时通过宏或其他编译器标志检查gcc的位域字节序实际上是什么?
The endianness of bitfields is implementation defined. Is there a way to check, at compile time, whether via some macro or other compiler flag, what gcc's bitfield endianness actually is?
换句话说,给定类似以下内容:
In other words, given something like:
struct X {
uint32_t a : 8;
uint32_t b : 24;
};
我是否有办法在编译时知道 a
是 X
中的第一个字节还是最后一个字节?
Is there a way for me to know at compile time whether or not a
is the first or last byte in X
?
推荐答案
在Linux系统上,您可以检查 __ BYTE_ORDER
宏以查看如果是 __ LITTLE_ENDIAN
或 __ BIG_ENDIAN
。
On Linux systems, you can check the __BYTE_ORDER
macro to see if it is __LITTLE_ENDIAN
or __BIG_ENDIAN
. While this is not authoritative, in practice it should work.
在 struct的定义中,暗示这是正确的方法netinet / ip.h中的iphdr
,用于IP标头。第一个字节包含两个4位字段,这些字段被实现为位字段,因此顺序很重要:
A hint that this is the right way to do it is in the definition of struct iphdr
in netinet/ip.h, which is for an IP header. The first byte contains two 4-bit fields which are implemented as bitfields, so the order is important:
struct iphdr
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
unsigned int ihl:4;
unsigned int version:4;
#elif __BYTE_ORDER == __BIG_ENDIAN
unsigned int version:4;
unsigned int ihl:4;
#else
# error "Please fix <bits/endian.h>"
#endif
u_int8_t tos;
u_int16_t tot_len;
u_int16_t id;
u_int16_t frag_off;
u_int8_t ttl;
u_int8_t protocol;
u_int16_t check;
u_int32_t saddr;
u_int32_t daddr;
/*The options start here. */
};
这篇关于gcc中的位域字节序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!