0

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.

Andre
  • 81
  • 6
  • What is you expectation regarding **"recursively"**? What have you tried so far? Have you looked at existing questions like [How to convert Hexadecimal to Decimal?](https://stackoverflow.com/questions/31079978/how-to-convert-hexadecimal-to-decimal) or [Converting Hexadecimal to Decimal](https://stackoverflow.com/questions/11031159/converting-hexadecimal-to-decimal) to understand how to do it? – David C. Rankin Jun 26 '19 at 01:35
  • Possible duplicate of [Converting Hexadecimal to Decimal](https://stackoverflow.com/questions/11031159/converting-hexadecimal-to-decimal) – David C. Rankin Jun 26 '19 at 01:37

2 Answers2

3

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.

J. S.
  • 425
  • 4
  • 13
  • You should **note:** that the hex string cannot include the prefixes `"0x"` or `"0X"` and the hex-characters must be upper-case (you can address the latter by including `` and using `std::tolower()` in your function). You can address the former in the caller or in a wrapper to your function that uses `.find()` to check for `'x'` or `'X'` and advances past the prefix. (for instance try converting `"11f"` or `"0x11F"`) That said, you did answer the "recursive" aspect of the question. – David C. Rankin Jun 26 '19 at 02:07
1

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);
}
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142