2015-10-06 38 views
0

我需要一个C++函数,它返回解释为bigendian long的四个连续字节的值。指向第一个字节的指针应该更新为指向最后一个字节。我曾尝试下面的代码:在C++中转换long-endian?

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

例如,如果p指向00 00 00 A0我希望的结果是160,但它是0。何以见得?

+0

[ntohl()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/ntohl.html)呢? –

+0

[将字节数组(char数组)转换为整数类型(short,int,long)]的可能重复(http://stackoverflow.com/questions/13678166/converting-byte-array-char-array-to-an -integer-type-short-int-long) –

+2

对'p'进行了多次修改,这些修改没有相对于对方进行排序。这是未定义的行为。 –

回答

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; 
} 

...将解决这个问题

+0

谢谢。我认为括号会解释明确的排序。我的编译器不给出警告。 – PAF

+0

括号确保算术的顺序,而不是++的副作用。该标准的措辞显式允许实现在使用p之后和下一个序列点(逗号或分号)之前的任何时候应用后增量。羞愧你没有警告。也许提高你的警告水平? –

0

这个函数在Unix和Windows上都被命名为ntohl()(将网络TO主机字节顺序转换为长),或者g_ntohl()在glib。之后将4添加到您的指针。如果你想推出自己的,一个联盟类型的成员是uint32_tuint8_t[4]将是有用的。