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

#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;//正常退出
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值