c++之进制转换16进制-10进制

本文讲解一种在c++中如何将16进制字符串转化成10进制,水平不高,但愿对你有帮助。一下便是源程序,包涵检错以及转化函数。前些日子帮一个朋友做笔试题,结果因为不熟悉这块的内容,只得了80分,自己好好安静下来写了一次,

#include<iostream>

#include<string>
using namespace std;
void check(string s);
void change(string &s);
bool flag = true;
void main()
{
    string a;
    while (flag)
    {
        cout << "please input" << endl;
        cin >> a;
        check(a);
    }
    change(a);
    

}
void check(string s)//检查输入的字符是否规范
{
    if (s.size() != 4)
    {
        cout << "input eoor" << endl;
    }
    else if (s[0] != '0')
    {
        cout << "input eoor" << endl;
    }
    else if (s[1]!='x'&&s[1]!='X')
    {
        cout << "input eoor" << endl;
    }
    else if (s[2]<'0'||s[2]>'f')
    {
        cout << "input eoor" << endl;
    }
    else if (s[3]<'0' || s[3]>'f')
    {
        cout << "input eoor" << endl;
    }
    else
    {
        flag=false;
    }
}
void change( string &s)//转化函数
{
    int a[2], result;
    for (int i = 2; i < 4; ++i)
    {
        if (s[i] <= '9')
        {
            a[i - 2] = s[i] - '0';
        }
        else
        {
            a[i - 2] = s[i] - 'a' + 10;
        }
    }
    result = a[0] * 16 + a[1];
    cout << "the result is" << result << endl;

}

因为字符‘0’-‘9’对应的数字是30-39,所以只需将原字符减去30或者‘0’就可以得到对应数字。但是‘a’-‘f’就不一样了,‘a’-‘a’对应的是0所以要加10

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值