10. 编码:写一个c函数,实现将16进制表现形式的字符串转化为整数。例如,输入”1a”,返回26,输入“FE”,返回254

#include <assert.h>
#include<iostream>
using namespace  std;

// 返回字符串的长度, 不包括最后\0
int string_len(const char *s)
{
    const char *p = s;
    while(*p != '\0')
        p++;
    return p - s;

}

int HexChar2Value(char c)
{
    // 如果字符是数字
    if (c > '0' && c <= '9')
        return c -'0';   
    else if (c >='a' && c <='f')
        return (c -'a' +10);
    else if(c >='A' && c <='F')
        return (c -'A' + 10);
    assert(0);                    //如果输入都不符合条件,提示错误,终止程序
    //cout << c <<endl;
    //cout<< (int) 'a' <<endl;
    return  0;
}

int hex_to_decimal(const char *szHex)
{
    int i;
    int result;             // 存放结果
    int len;                //字符串长度,不包括\0
    int value;            //保存字符串转化为整形的数值
    result = 0;        

    len = string_len(szHex);   //获取字符串长度

    for(i =0; i < len ;i++)
    {
          value = HexChar2Value(szHex[i]);                   //字符串转化为整形数值
            result += pow((double) 16, (int)len -i -1) * value;       //从最高位开始计算
    }
    return result;
}

int main()
{
    int result;
     result = hex_to_decimal("f1");    //输入一个字符串 0x1001, 返回一个int数
     cout << result <<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值