hex to decimal with two methods istringstream is so slow

本文介绍了一种将十六进制字符串转换为十进制数值的方法,并提供了两种实现方式:一种是通过手动解析每个字符并计算其对应的十进制值;另一种是利用标准库函数进行转换。通过对这两种方法的性能比较,展示了不同实现方式的效率差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
#include <algorithm>
using namespace std;
int convert(char ch) {
    if (isdigit(ch)) {
        return ch - '0';
    }
    if (isupper(ch)) {
        return ch - 'A' + 10;
    }
    if (islower(ch)) {
        return ch - 'a' + 10;
    }
    return -1;
}
long hex_str_to_dec_num(const char *hex_str) {
    long sum = 0;
    long t = 1;
    int len = strlen(hex_str);
    for (int i = len - 1;i >= 0;i--) {
        sum += t * convert(hex_str[i]);
        t = t << 4;
    }
    return sum;
}
long hex_str_to_dec_num1(const char *hex_str) {
    long value = 0;
    istringstream ss(hex_str);
    ss >> std::hex >> value;
    return value;
}
int main() {
    for (int i = 0;i < 1000000;i++) {
//      hex_str_to_dec_num("A1BCA1");       // 0.108s
        hex_str_to_dec_num1("A1BCA1");      // 0.965s
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值