首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C中的二进制到十进制

C中的二进制到十进制
EN

Stack Overflow用户
提问于 2012-09-09 19:11:37
回答 5查看 37.5K关注 0票数 3

我有一个简单的代码来转换二进制到十进制数。在我的编译器中,分解对于小于1000的数字工作得很好,超过了输出总是相同的1023。有谁有主意吗?

代码语言:javascript
运行
复制
#include <stdio.h>
#include <stdlib.h>

// how many power of ten is there in a number 
// (I don't use the pow() function to avoid trouble with floating numbers)
int residu(int N)
{
    int i=0;
    while(N>=1){
        N=N/10;
        i++;
    }
    return i;
}

//exponentiating a number a by a number b
int power(int a, int b){
    int i;
    int res=1;
    for (i=0;i<b;i++){res=a*res;}
    return res;
}

//converting a number N
int main()
{
    int i;

    //the number to convert
    int N;
    scanf("%d",&N);

    //the final decimal result
    int res=0;
    //we decompose N by descending powers of 10, and M is the rest
    int M=0;

    for(i=0;i<residu(N);i++){
        // simple loop to look if there is a power of (residu(N)-1-i) in N, 
        // if yes we increment the binary decomposition by 
        // power(2,residu(N)-1-i)
        if(M+ power(10,residu(N)-1-i) <= N)
        {
            M = M+power(10,residu(N)-1-i);
            res=power(2,residu(N)-1-i)+res;
        }
    }
    printf("%d\n",res);
}
EN

Stack Overflow用户

发布于 2012-09-09 23:56:39

左移与乘2相同,而且效率更高,所以我认为这是一个更类似于c的答案:

代码语言:javascript
运行
复制
#include <stdio.h>
#include <stdlib.h>

int bin2int(const char *bin) 
{
    int i, j;
    j = sizeof(int)*8;
    while ( (j--) && ((*bin=='0') || (*bin=='1')) ) {
        i <<= 1;
        if ( *bin=='1' ) i++;
        bin++;
    }
    return i;
}

int main(void) 
{ 
    char* input = NULL;
    size_t size = 0;

    while ( getline(&input, &size, stdin) > 0 ) {
        printf("%i\n", bin2int(input)); 
    }
    free(input);
}
票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12338584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档