I am trying to convert a number from base b to base 10 using the function base_b_to_10 as below:
long int base_b_to_10(char* B, long int base) //take in the number as string returns it converted to base 10 as long int
{
long int N; //base 10 number:
N = strtol(B, NULL, base); //
return(N);
}
In the main program, the user will input the base of the input number and the input number itself. The length and the size of the string is unknown and is up to the user to define This is a simplified version of a big program I am trying to build in which the size of the string B is dynamically allocated in another function so I cannot do something like:
char B[100];
How to solve this? the compiler is returning nothing.
CodePudding user response:
Input string (here: test
) can be of any reasonable size. Anyway, there might be some limitations, see: Strtol() and atol() do not convert strings larger than 9 digits
Output string is a pointer (here: *str
) to position within input string (here: test
). According to this, the size of the string to which str
points does not matter. (Note: In this example, str
is only valid as long as test
is valid).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long int base_b_to_10(char* B, long int base, char **ret_str)
{
long int N;
N = strtol(B, ret_str, base);
return N;
}
int main()
{
long int val;
char *str;
char test[50] = "43724325HelloWorld";
val = base_b_to_10(test, 10, &str);
printf("val = %ld\n", val);
printf("str = %s\n", str);
return 1;
}
Notes: I adapted your example just to be working (not improving or simplifying anything). It is probably clear that you could also directly use strtol
function in the main routine. Moreover, it does not matter, how the input string was allocated (fixed size or dynamic size) - just needs to be allocated and needs to end by \0
(as usual).
CodePudding user response:
If cross platforming is not an issue, and assuming you are running on a linux system, you can make use of asprintf().
It basically formats your string and allocates the memory for you (remember to free it afterwards).
This is not part of the standard library so it has its limitations.
- Another approach is to use snprintf() to preddict the size of the output buffer then and use malloc()
#include <stdio.h>
int main ()
{
int cx = snprintf ( NULL, 0, "18 characters long" );
printf("%d", cx);
return 0;
}
// OUTPUT:
// 18