【问题标题】:Is NetworkByteOrder is the same as Big endian?NetworkByteOrder 是否与 Big endian 相同?
【发布时间】:2019-04-16 02:30:48
【问题描述】:

我创建一个演示来证明网络字节顺序与大端相同:

#include "stdio.h"
#include "stdint.h"
#include "winsock2.h"
#define BL32(x)  ((((x) & 0x000000ffUL) << 24) | \
                 (((x) & 0x0000ff00UL) <<  8) | \
                 (((x) & 0x00ff0000UL) >>  8) | \
                 (((x) & 0xff000000UL) >> 24))
int main(int argc, char* argv[])
{
    uint32_t s = INT_MAX; // little endian
    uint32_t network = htonl(s);
    uint32_t bigendian = BL32(s);
    if(network == bigendian) {
        printf("nbo is same as big endian\n");
    } else {
        printf("nbo isn't same as big endian\n");
    }

    return 0;
}

这个程序在 x86(litte endian) Windows PC 上运行,它会给出输出:

nbo is same as big endian

我没有看到教科书或教程中提到这一点,所以我想确认它是否正确。

顺便说一句,我认为帮助理解网络中的字节顺序非常重要。为什么大多数问题只集中在“大端与小端”...

【问题讨论】:

    标签: c sockets network-programming


    【解决方案1】:

    是的,是的。你可以在Endianness的维基百科文章中阅读它

    Big-endian 是数据网络中最常见的格式; Internet 协议族协议中的 IPv4、IPv6、TCP 和 UDP 等字段按照大端顺序传输。因此,大端字节序也称为网络字节序

    您通常不需要知道网络字节顺序是大端还是小端。只需使用ntohXhtonX 宏,它就会做正确的事情。如果您使用的硬件与网络协议具有相同的字节顺序,它将不理会该值;如果你在一个字节顺序相反的机器上,它会交换字节。

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 2019-06-30
      • 2014-05-25
      • 1970-01-01
      • 2018-05-15
      • 2022-06-10
      相关资源
      最近更新 更多