C : converting binary to decimal

后端 未结 2 1054
难免孤独
难免孤独 2021-01-23 08:05

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条回答
  • 2021-01-23 08:27

    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.

    0 讨论(0)
  • 2021-01-23 08:31

    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.

    0 讨论(0)
提交回复
热议问题