您的位置:首页 > 编程语言 > C语言/C++

c++常用函数之 十六进制字符串转换为十进制

2013-06-26 16:19 375 查看
#include <iostream>

#include <math.h>

#include <string>

using namespace std;

int HexToDec(const string str,int& n){

if (str.empty())

{

return 1;//字符串为空

}

if (str.length()>8)

{

return 2;//超出范围

}
char* pc = new char[str.length()];

if (pc==NULL)

{

return -2;//内存申请失败

}

memset(pc,0,str.length());

str.copy(pc,2);

string strTmp(pc);

int cpyCount=0;

memset(pc,0,str.length());

if (strTmp.compare("0x")==0 || strTmp.compare("0X")==0)

{

cpyCount = str.copy(pc,str.size()-2,2);

}else{

cpyCount = str.copy(pc,str.size());

}

n=0;

char *ptmp = pc;

for (int i=0;i<cpyCount;i++)

{

if (*pc>='0' && *pc<='9'){

n += (*pc-'0')*static_cast<int>(pow(16,cpyCount-i-1));

}else if (*pc>='A' && *pc<='F'){

n += (*pc-'A'+10)*static_cast<int>(pow(16,cpyCount-i-1));

}else if (*pc>='a' && *pc<='f'){

n += (*pc-'a'+10)*static_cast<int>(pow(16,cpyCount-i-1));

}else{

return -1;//含有非法字符

}

pc++;

}

pc = ptmp;

delete []pc;

pc=NULL;

return 0;//正常退出

}

第二中实现方法

int HexToDec(const string str,int& n){

if (str.empty())

{

return 1;//字符串为空

}

if (str.length()>8)

{

return 2;//超出范围

}

char* pc = new char[str.length()];

if (pc==NULL)

{

return -2;//内存申请失败

}

memset(pc,0,str.length());

str.copy(pc,2);

string strTmp(pc);

int cpyCount=0;

memset(pc,0,str.length());

if (strTmp.compare("0x")==0 || strTmp.compare("0X")==0)

{

cpyCount = str.copy(pc,str.size()-2,2);

}else{

cpyCount = str.copy(pc,str.size());

}

n=0;

char *ptmp = pc;

int mid;

for (int i=0;i<cpyCount;i++)

{

if (*pc>='0' && *pc<='9'){

mid = *pc-'0';

}else if (*pc>='A' && *pc<='F'){

mid = *pc-'A'+10;

}else if (*pc>='a' && *pc<='f'){

mid = *pc-'a'+10;

}else{

return -1;//含有非法字符

}

mid <<= ((cpyCount-i-1)<<2);//用移位方式实现 ((cpyCount-i-1)<<2)这样做的目的就是因为二进制每四位组成十六进制的一个位

n += mid;

pc++;

}

pc = ptmp;

delete []pc;

pc=NULL;

return 0;//正常退出

}

if (str.length()>8)

{

return 2;//超出范围

}

第三种做法
int HexToDec(const string str,int& n){

if (str.empty())

{

return 1;//字符串为空

}

if (str.length()>8)

{

return -1;//超出范围

}

string strTmp;

strTmp = str.substr(0,2);

if (strTmp.compare("0x")==0 || strTmp.compare("0X")==0)

{

strTmp = str.substr(2,str.length()-2);

}else{

strTmp = str;

}

n=0;

char *pc = const_cast<char*>(strTmp.c_str());

int cpyCount=strTmp.length();

int mid;

for (int i=0;i<cpyCount;i++)

{

if (*pc>='0' && *pc<='9'){

mid = *pc-'0';

}else if (*pc>='A' && *pc<='F'){

mid = *pc-'A'+10;

}else if (*pc>='a' && *pc<='f'){

mid = *pc-'a'+10;

}else{

return -1;//含有非法字符

}

mid <<= ((cpyCount-i-1)<<2);

n += mid;

pc++;

}

return 0;//正常退出

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐