我们正在编写嵌入式应用程序代码并验证字符串是否具有有效的 IPv4 格式。我可以使用字符串分词器成功地做到这一点,但现在我需要使用 htonl() 函数将整数转换为主机到网络顺序。
由于它是一个嵌入式应用程序,我不能仅仅为了使用 htonl() 函数而包含网络 header 和库。
C++ 中是否有任何方法/非网络 header 可以利用 htonl() 功能?
最佳答案
来自htonl()
的手册页:
The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.
Network byte order实际上只是大端。
您需要做的就是编写(或找到)一个将无符号整数转换为大端字节序的函数,并使用它来代替 htonl
。如果您的系统已经采用大端字节序,那么您根本不需要执行任何操作。
您可以使用以下内容来确定系统的字节顺序:
int n = 1;
// little endian if true
if(*(char *)&n == 1) {...}
您可以使用以下命令将小端字节序 uint32_t
转换为大端字节序:
uint32_t htonl(uint32_t x) {
unsigned char *s = (unsigned char *)&x;
return (uint32_t)(s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]);
}
关于c++ - htonl 不使用网络相关 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50167471/