2

Is there any dedicated function for converting the binary values to decimal values. such as (1111 to 15 ) , ( 0011 to 3 ) .

Thanks in Advance

2
  • How are you getting these binary numbers? like int i = 10011; // not really binary or a string?
    – GManNickG
    Commented Mar 20, 2010 at 6:43
  • yea ,it will be string only...
    – Pavunkumar
    Commented Mar 20, 2010 at 6:54

2 Answers 2

7

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.

1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.