问题
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