简体   繁体   English

C:将二进制转换为十进制

[英]C : converting binary to decimal

Is there any dedicated function for converting the binary values to decimal values. 是否有用于将二进制值转换为十进制值的专用功能。 such as (1111 to 15 ) , ( 0011 to 3 ) . 例如(1111至15),(0011至3)。

Thanks in Advance 提前致谢

Yes, the strtol function has a base parameter you can use for this purpose. 是的, strtol函数具有可用于此目的的base参数。

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). 这样可以正确解析并打印整数25(二进制为11001 )。 The error handling of strtol allows noticing when parts of the string can't be parsed as an integer in the desired base. strtol的错误处理允许在无法将字符串的某些部分解析为所需基数中的整数时发出通知。 You'd want to learn more about this by reading in the reference I've linked to above. 您想通过阅读上面链接到的参考文献来了解更多信息。

Parse it with strtol , then convert to a string with one of the printf functions. 使用strtol对其进行解析,然后使用printf函数之一将其转换为字符串。 Eg 例如

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. 这会分配比所需更多的空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM