C:二进制转换为十进制 [英] C : converting binary to decimal

查看:185
本文介绍了C:二进制转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有转换二进制值转换为十进制值的任何专门的功能。
如(1111〜15),(0011〜3)。

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

由于提前

推荐答案

是的, strtol将函数有一个参数可用于这一目的。

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;
}

这正确分析和打印整数25(这是 11001 二进制)。 与strtol 的错误处理允许注意到,当部分字符串不能被解析为在所需的基本整数。你会希望通过我联系到上面的参考阅读,了解更多关于这一点。

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.

这篇关于C:二进制转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆