从字节数组解出int64_t值

来源:互联网 发布:软件编程技术 编辑:程序博客网 时间:2024/06/05 19:11

通常解析一个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位数的时候就会出错。

0 0