c - 使用 htons 确定字节顺序

标签 c linux network-programming endianness

考虑以下代码:

#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(以及ntohshtonlntohl)作为空操作,而在小端系统上,它们执行字节交换。

编辑:

这也可以使用 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/

相关文章:

c - (C) 模拟 main 中代码块的函数

linux - 如何在行本身旁边添加相同行的数量?

Python收发RTP包

php - 如何通过stream_get_contents()连续监听多个TCP流?

c - C 中数字的唯一组合

c - 为什么我不能将 real[0] 分配给 x 的地址

c - 通过 C 代码使用 ssh

c++ - Boost.Asio 在尝试加入多播组时抛出 'No such device' 异常

无法使用 fscanf 正确读取

linux - 如何从源代码安装内核模块。制作过程中出错