Binary to decimal in c

I have a simple code to convert binary to decimal numbers. In my compiler, the decomposition works just fine for number less than 1000, beyond the output is always the same 1023. Anybody has an idea ?

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

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

        // 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);


Yes try this :

#include <stdio.h>
int main(void) 
char bin; int dec = 0;

while (bin != '\n') { 
if (bin == '1') dec = dec * 2 + 1; 
else if (bin == '0') dec *= 2; } 

printf("%d\n", dec); 

return 0;


Most likely this is because you are using an int to store your binary number. An int will not store numbers above 2^31, which is 10 digits long, and 1023 is the largest number you can get with 10 binary digits.

It would be much easier for you to read your input number as a string, and then process each character of the string.

Need Your Help

Deserialize Json Array using Newtonsoft.Json

c# json serialization

I have an array of objects like this in json as per below format

Using Grunt to process handlebar template files into mysql database

mysql file gruntjs handlebars.js

I'm looking to use grunt to process templates (handlebars and static html files) into a mysql database table. I currently use grunt to compile handlebar templates on the client side. However, we need

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.