考虑以下代码:
#include <stdio.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
uint16_t num = 123;
if (htons(num) == num) {
printf("big endian\n");
} else {
printf("little endian\n");
}
}
我想知道这段代码是否适用于检查字节顺序?我已经看到很多问题用各种指针/字符技巧来检查它,但我认为这更简单。它假设如果将数字转换为网络字节顺序(大端),如果它与原始数字相同,那么您就在大端系统上。否则,您使用的是小端系统。
此检查是否存在错误假设?尽管 it seems it is standardised to be so,也许网络字节顺序并不总是大端。 .
最佳答案
这足以在运行时检查字节顺序。
在大端系统上,定义了htons
(以及ntohs
、htonl
和ntohl
)作为空操作,而在小端系统上,它们执行字节交换。
编辑:
这也可以使用 union 来完成。下面的检查检测大端和小端,以及其他更奇特的字节顺序。
#include <stdio.h>
#include <stdint.h>
union echeck {
uint32_t i;
char c[4];
} echeck = { .c = { 0x01, 0x02, 0x03, 0x04 } };
int main()
{
if (echeck.i == 0x01020304) {
printf("big endian\n");
} else if (echeck.i == 0x04030201) {
printf("little endian\n");
} else if (echeck.i == 0x02010403) {
printf("pdp endian\n");
} else {
printf("other endian\n");
}
return 0;
}
关于c - 使用 htons 确定字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41390190/