C宏定义确定大端或小端机?是否有一行宏定义来确定机器的字节顺序。我使用以下代码,但将其转换为宏将太长。unsigned char test_endian( void ){
int test_var = 1;
unsigned char test_endian* = (unsigned char*)&test_var;
return (test_endian[0] == NULL);}
3 回答
慕妹3242003
TA贡献1824条经验 获得超6个赞
支持任意字节顺序的代码,准备放入一个名为的文件中order32.h
:
#ifndef ORDER32_H#define ORDER32_H#include <limits.h>#include <stdint.h>#if CHAR_BIT != 8#error "unsupported char size"#endifenum{ O32_LITTLE_ENDIAN = 0x03020100ul, O32_BIG_ENDIAN = 0x00010203ul, O32_PDP_ENDIAN = 0x01000302ul, /* DEC PDP-11 (aka ENDIAN_LITTLE_WORD) */ O32_HONEYWELL_ENDIAN = 0x02030001ul /* Honeywell 316 (aka ENDIAN_BIG_WORD) */};static const union { unsigned char bytes[4]; uint32_t value; } o32_host_order = { { 0, 1, 2, 3 } };#define O32_HOST_ORDER (o32_host_order.value)#endif
您将检查通过的小端系统
O32_HOST_ORDER == O32_LITTLE_ENDIAN
至尊宝的传说
TA贡献1789条经验 获得超10个赞
如果您有一个支持C99复合文字的编译器:
#define IS_BIG_ENDIAN (!*(unsigned char *)&(uint16_t){1})
要么:
#define IS_BIG_ENDIAN (!(union { uint16_t u16; unsigned char c; }){ .u16 = 1 }.c)
通常,您应该尝试编写不依赖于主机平台的字节顺序的代码。
与host-endianness无关的实现示例ntohl()
:
uint32_t ntohl(uint32_t n){ unsigned char *np = (unsigned char *)&n; return ((uint32_t)np[0] << 24) | ((uint32_t)np[1] << 16) | ((uint32_t)np[2] << 8) | (uint32_t)np[3];}
- 3 回答
- 0 关注
- 804 浏览
添加回答
举报
0/150
提交
取消