How to convert hexadecimal to decimal recursively [closed]

我的未来我决定 提交于 2021-01-29 05:30:48

问题


I need to do this convertion but have no clue. Can someone help me? I need this to complete a calculator of base convertion. I also need that the function return a integer to convert to use in my others functions.

PS: sorry for my bad english.

i expect that 11F to be an integer 287.


回答1:


Here's something with recursion:

int hexToBase10(const std::string& number, size_t pos = 0) {
   if (pos == number.length())
       return 0;
   char digit = number[number.size() - pos - 1];
   int add = digit >= '0' && digit <= '9' ? digit - '0'
                                          : digit - 'A' + 10;
   return 16 * hexToBase10(number, pos + 1) + add;
}

Call it this way:

hexToBase10("11F");  // 287

Btw, it seems to be more safe to use std::hex.




回答2:


Provided it fits into at most unsigned long long, you can use strtoul/strtoull from stdlib.h to parse it from a base-16 string into an integer.

You can then simply print that integer in base 10.

#include <stdlib.h>
#include <stdio.h>
int main()
{
    char const *hex = "11F";
    char *endptr;
    unsigned long ul = strtoul(hex,&endptr,16);
    printf("%lu\n", ul);
}


来源:https://stackoverflow.com/questions/56763669/how-to-convert-hexadecimal-to-decimal-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!