[英]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. 您想通过阅读上面链接到的参考文献来了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.