猿问

C宏定义确定大端或小端机?

C宏定义确定大端或小端机?

是否有一行宏定义来确定机器的字节顺序。我使用以下代码,但将其转换为宏将太长。

unsigned char test_endian( void ){
    int test_var = 1;
    unsigned char test_endian* = (unsigned char*)&test_var;

    return (test_endian[0] == NULL);}


慕桂英546537
浏览 805回答 3
3回答

慕妹3242003

支持任意字节顺序的代码,准备放入一个名为的文件中order32.h:#ifndef&nbsp;ORDER32_H#define&nbsp;ORDER32_H#include&nbsp;<limits.h>#include&nbsp;<stdint.h>#if&nbsp;CHAR_BIT&nbsp;!=&nbsp;8#error&nbsp;"unsupported&nbsp;char&nbsp;size"#endifenum{ &nbsp;&nbsp;&nbsp;&nbsp;O32_LITTLE_ENDIAN&nbsp;=&nbsp;0x03020100ul, &nbsp;&nbsp;&nbsp;&nbsp;O32_BIG_ENDIAN&nbsp;=&nbsp;0x00010203ul, &nbsp;&nbsp;&nbsp;&nbsp;O32_PDP_ENDIAN&nbsp;=&nbsp;0x01000302ul,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/*&nbsp;DEC&nbsp;PDP-11&nbsp;(aka&nbsp;ENDIAN_LITTLE_WORD)&nbsp;*/ &nbsp;&nbsp;&nbsp;&nbsp;O32_HONEYWELL_ENDIAN&nbsp;=&nbsp;0x02030001ul&nbsp;/*&nbsp;Honeywell&nbsp;316&nbsp;(aka&nbsp;ENDIAN_BIG_WORD)&nbsp;*/};static&nbsp;const&nbsp;union&nbsp;{&nbsp;unsigned&nbsp;char&nbsp;bytes[4];&nbsp;uint32_t&nbsp;value;&nbsp;}&nbsp;o32_host_order&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;{&nbsp;0,&nbsp;1,&nbsp;2,&nbsp;3&nbsp;}&nbsp;};#define&nbsp;O32_HOST_ORDER&nbsp;(o32_host_order.value)#endif您将检查通过的小端系统O32_HOST_ORDER&nbsp;==&nbsp;O32_LITTLE_ENDIAN

至尊宝的传说

如果您有一个支持C99复合文字的编译器:#define&nbsp;IS_BIG_ENDIAN&nbsp;(!*(unsigned&nbsp;char&nbsp;*)&(uint16_t){1})要么:#define&nbsp;IS_BIG_ENDIAN&nbsp;(!(union&nbsp;{&nbsp;uint16_t&nbsp;u16;&nbsp;unsigned&nbsp;char&nbsp;c;&nbsp;}){&nbsp;.u16&nbsp;=&nbsp;1&nbsp;}.c)通常,您应该尝试编写不依赖于主机平台的字节顺序的代码。与host-endianness无关的实现示例ntohl():uint32_t&nbsp;ntohl(uint32_t&nbsp;n){ &nbsp;&nbsp;&nbsp;&nbsp;unsigned&nbsp;char&nbsp;*np&nbsp;=&nbsp;(unsigned&nbsp;char&nbsp;*)&n; &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;((uint32_t)np[0]&nbsp;<<&nbsp;24)&nbsp;| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;((uint32_t)np[1]&nbsp;<<&nbsp;16)&nbsp;| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;((uint32_t)np[2]&nbsp;<<&nbsp;8)&nbsp;| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(uint32_t)np[3];}
随时随地看视频慕课网APP
我要回答