Qt使用第三方库GMP,用以超长整数运算

来源:互联网 发布:小米批量卸载软件 编辑:程序博客网 时间:2024/06/05 10:22
  GMP是开源的数学运算库。当Qt自带的qint64(依赖系统位数)也满足不了长度时,可以用它进行数据计算。
    最近写的下载器中,当下载到2点几G时,突然出现startPoint与endPoint变为负数,导致http的Range请求头部出错。网上一查,原来是整数溢出。如下代码:

qint64 startPoint=0;qint64 endPoint=0;int index=-1; if((index = sectionList.indexOf("-1")) != -1){     if(index == (sectionList.count()-1))      {           startPoint = index*bufferSize;            endPoint = totalBytesCount;      }else       {            startPoint = qint64(index*bufferSize);//大到一定值,这里最先溢出            endPoint = qint64((index+1)*bufferSize-1);        }     sectionList.replace(index,"0");     thread->receiveTask(index,this->realUrl,startPoint,endPoint);}
编译GMP:
到http://gmplib.org/官网下载源码包。
解包后进入解压目录。执行:

./configure --enable-cxxmakemake check  sudo make install

安装完成。

Qt中使用:
pro中添加:
LIBS += -lgmpxx -lgmp
项目中的环境变量添加:
LD_LIBRARY_PATH    /usr/local/lib

基本使用示例
#include<gmp.h>#include<stdio.h>char* BigMul(char* m,char* n);void main(){char* p=NULL;char *a="12345678";char *b="23456789";p=BigMul(a,b);printf("the result is %s./n",p);}char* BigMul(char* m,char* n){int i,j;char* pt=NULL;mpz_t s,p,q;        mpz_init(s);i=mpz_init_set_str(p,m,10);//get number from mj=mpz_init_set_str(q,n,10);//printf("i,j:%d,%d\n",i,j);gmp_printf("%Zd\n%Zd\n",p,q);mpz_addmul(s,p,q);//calculate result//gmp_printf("the result is %Zd\n",s);pt=mpz_get_str(pt,10,s);//get string from s//printf("%s\n",pt);mpz_clear(s);return pt;}
0 0