在C ++中转换big-endian long?

时间:2015-10-06 07:20:03

标签: c++ bit-shift endianness integer-promotion

我需要一个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.为什么?

2 个答案:

答案 0 :(得分: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;
}

......将解决它

答案 1 :(得分:0)

This function is named ntohl() (convert Network TO Host byte order Long) on both Unix and Windows, or g_ntohl() in glib. Add 4 to your pointer afterward. If you want to roll your own, a union type whose members are a uint32_t and a uint8_t[4] will be useful.