我正在编写自己的htonl,htons,ntohl和ntohs函数,并且出现了我不了解的行为。下面的代码按预期工作:
uint16_t htons(uint16_t hostshort)
{
uint16_t netshort = 0;
uint8_t* p = (uint8_t*) (&netshort);
p[0] = (uint8_t)((hostshort & 0xFF00) >> 8);
p[1] = (uint8_t)((hostshort & 0x00FF) >> 0);
return netshort;
}
uint16_t ntohs(uint16_t netshort)
{
uint16_t hostshort = 0;
uint8_t* p = (uint8_t*) netshort;
hostshort |= ((uint16_t)p[0]) << 8;
hostshort |= ((uint16_t)p[1]) << 0;
return hostshort;
}
问题在于此代码根本不起作用:
uint16_t htons(uint16_t hostshort)
{
uint16_t netshort = 0;
uint8_t* p = (uint8_t*) netshort;
p[0] = (uint8_t)((hostshort & 0xFF00) >> 8);
p[1] = (uint8_t)((hostshort & 0x00FF) >> 0);
return netshort;
}
uint16_t ntohs(uint16_t netshort)
{
uint16_t hostshort = 0;
uint8_t* p = (uint8_t*) (&netshort);
hostshort |= ((uint16_t)p[0]) << 8;
hostshort |= ((uint16_t)p[1]) << 0;
return hostshort;
}
当我从htons的netshort中删除&时,它返回全零,而当我在ntohs中添加它时,它返回垃圾。有人可以解释一下他们的处理方式吗?我的理解是,这两种情况都应返回一个指向内存中数据开头的指针,但是显然它们的处理方式不同。参数是否隐式发生了什么?
最佳答案
uint16_t netshort = 0;
uint8_t* p = (uint8_t*) netshort;
也就是说,采用netshort的值(即
0
),并将其解释为uint8_t*
指针。在这种情况下,该值将为null。这意味着未定义为该指针分配内容的以下几行。
p[0] = (uint8_t)((hostshort & 0xFF00) >> 8);
p[1] = (uint8_t)((hostshort & 0x00FF) >> 0);
您需要获取当地的地址。
uint8_t* p = (uint8_t*) &netshort;
关于c++ - C++对局部变量的引用与对参数的引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35997230/