将16进制表现形式的字符串转化为整数

#include <iostream>
#include <string>
#include <vector>
#include <cmath>

int hex2int(const std::string &hex) {
    std::string::const_reverse_iterator rit=hex.rbegin();
    int i=0, ret=0;
    for(; rit!=hex.rend(); ++rit) {
        if(*rit >= '0' && *rit <= '9') {
            ret += (*rit - '0') * pow(16, i);
        }
        else if(*rit >= 'a' && *rit <= 'f') {
            ret += (*rit - 'a' + 10) * pow(16, i);
        }
        else {
            ret += (*rit - 'A' + 10) * pow(16, i);
        }
        i++;
    }

    return ret;
}

int main() {
    std::vector<std::string> v_s;
    v_s.push_back("12a");
    v_s.push_back("ef");
    v_s.push_back("a1");
    v_s.push_back("2a3");
    v_s.push_back("A1");

    for(std::vector<std::string>::const_iterator cit=v_s.begin(); cit!=v_s.end(); ++cit) {
        std::cout<<"16进制: "<<*cit<<"  10进制: "<<hex2int(*cit)<<std::endl;
    }

    return 0;
}

转载于:https://www.cnblogs.com/donggongdechen/p/11436763.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值