Is there any dedicated function for converting the binary values to decimal values. such as (1111 to 15 ) , ( 0011 to 3 ) .
Thanks in Advance
Parse it with strtol, then convert to a string with one of the printf functions. E.g.
char binary[] = "111";
long l = strtol(binary, 0, 2);
char *s = malloc(sizeof binary);
sprintf(s, "%ld\n", l);
This allocates more space than needed.
Yes, the strtol function has a base
parameter you can use for this purpose.
Here's an example with some basic error handling:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* input = "11001";
char* endptr;
int val = strtol(input, &endptr, 2);
if (*endptr == '\0')
{
printf("Got only the integer: %d\n", val);
}
else
{
printf("Got an integer %d\n", val);
printf("Leftover: %s\n", endptr);
}
return 0;
}
This correctly parses and prints the integer 25 (which is 11001
in binary). The error handling of strtol
allows noticing when parts of the string can't be parsed as an integer in the desired base. You'd want to learn more about this by reading in the reference I've linked to above.