0

我需要一个 C++ 函数,它返回解释为 bigendian long 的四个连续字节的值。指向第一个字节的指针应该更新为指向最后一个字节之后。我尝试了以下代码:

inline int32_t bigendianlong(unsigned char * &p)  
{  
  return (((int32_t)*p++ << 8 | *p++) << 8 | *p++) << 8 | *p++;  
}  

例如,如果 p 指向 00 00 00 A0,我希望结果是 160,但它是 0。怎么会?

4

2 回答 2

2

这个警告清楚地解释了这个问题(由编译器发出):

./endian.cpp:23:25: warning: multiple unsequenced modifications to 'p' [-Wunsequenced]
    return (((int32_t)*p++ << 8 | *p++) << 8 | *p++) << 8 | *p++;

分解函数中的逻辑以明确指定序列点...

inline int32_t bigendianlong(unsigned char * &p)
{
    int32_t result = *p++;
    result = (result << 8) + *p++;
    result = (result << 8) + *p++;
    result = (result << 8) + *p++;
    return result;
}

……会解决的

于 2015-10-06T07:57:08.780 回答
0

此函数ntohl()在 Unix 和 Windows 或g_ntohl()glib 中都被命名为 (convert Network TO Host byte order Long)。之后将 4 添加到您的指针。如果您想自己滚动,则成员为 auint32_t和 a的联合类型uint8_t[4]将很有用。

于 2015-10-06T08:19:31.833 回答