我正在写自己的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;
}
当我删除&amp;从netshort in htons,它返回所有零,当我在ntohs中添加它时,它返回垃圾。有人可以解释他们的处理方式有何不同?我的理解是两个案例都应该返回一个指向内存中数据开头的指针,但显然它们的处理方式不同。参数是否隐含发生了什么?
答案 0 :(得分:0)
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;