NetworkByteOrder 是否与 Big endian 相同?
Is NetworkByteOrder is the same as Big endian?
我创建了一个演示来证明网络字节顺序与大端相同:
#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(小端)Windows PC 上运行,并给出输出:
nbo is same as big endian
我没看到课本和教程中提到这个,所以我想确认一下是否正确。
顺便说一句,我认为帮助理解什么是网络中的字节顺序非常重要。为什么大部分问题只集中在 "big vs little endian"...
是的,是的。您可以在 Endianness
上的维基百科文章中阅读它
Big-endian is the most common format in data networking; fields in the protocols of the Internet protocol suite, such as IPv4, IPv6, TCP, and UDP, are transmitted in big-endian order. For this reason, big-endian byte order is also referred to as network byte order.
您通常不需要知道网络字节顺序是大端还是小端。只需使用 ntohX
和 htonX
宏,它就会做正确的事情。如果您使用的硬件与网络协议具有相同的字节顺序,它会保留该值;如果你在一台字节顺序相反的机器上,它会交换字节。
我创建了一个演示来证明网络字节顺序与大端相同:
#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(小端)Windows PC 上运行,并给出输出:
nbo is same as big endian
我没看到课本和教程中提到这个,所以我想确认一下是否正确。
顺便说一句,我认为帮助理解什么是网络中的字节顺序非常重要。为什么大部分问题只集中在 "big vs little endian"...
是的,是的。您可以在 Endianness
上的维基百科文章中阅读它Big-endian is the most common format in data networking; fields in the protocols of the Internet protocol suite, such as IPv4, IPv6, TCP, and UDP, are transmitted in big-endian order. For this reason, big-endian byte order is also referred to as network byte order.
您通常不需要知道网络字节顺序是大端还是小端。只需使用 ntohX
和 htonX
宏,它就会做正确的事情。如果您使用的硬件与网络协议具有相同的字节顺序,它会保留该值;如果你在一台字节顺序相反的机器上,它会交换字节。