通常解析一个int大小的变量,用下面的函数:
static inline int parseInt(char *p)
{
return ((0xff & *(p+0)) << 0)
| ((0xff & *(p+1)) << 8)
| ((0xff & *(p+2)) << 16)
| ((0xff & *(p+3)) << 24);
}
如果解析一个int64_t的变量,用下面的函数就不行:
static inline int64_t parseInt64(char *p)
{
return ((0xff & *(p+0)) << 0)
| ((0xff & *(p+1)) << 8)
| ((0xff & *(p+2)) << 16)
| ((0xff & *(p+3)) << 24)
| ((0xff & *(p+4)) << 32)
| ((0xff & *(p+5)) << 40)
| ((0xff & *(p+6)) << 48)
| ((0xff & *(p+7)) << 56);
}
而要用下面的函数才行:
static inline int64_t parseInt64(char *p)
{
return ((0xff & (int64_t)*(p+0)) << 0)
| ((0xff & (int64_t)*(p+1)) << 8)
| ((0xff & (int64_t)*(p+2)) << 16)
| ((0xff & (int64_t)*(p+3)) << 24)
| ((0xff & (int64_t)*(p+4)) << 32)
| ((0xff & (int64_t)*(p+5)) << 40)
| ((0xff & (int64_t)*(p+6)) << 48)
| ((0xff & (int64_t)*(p+7)) << 56);
}
函数里的“|”可以改成“+”,是一样的。重要的是进行类型扩展,系统默认是扩展到4个字节的宽度,这样在解64位数的时候就会出错。