Everything works fine until I enter a binary number that has more than 10 digits. In that case, if I enter eleven '1's, sum will equal 1024 (which is the 10th power of 2) and its not adding the rest. I used a print statement to show this. Whats going on?
Code:
#include <stdio.h>
#include <string.h>
int main(){
char number[50];
puts("Enter Binary Number: ");
scanf("%s", number);
int length = strlen(number);
int remainder = 0, div = 1, idx = 0,
array[length], i, l, num = atoi(&number);
for(i = 1; i < length; i++){
div *= 10;
}
while(num){
remainder = num/div;
num = num % div;
div = div/10;
array[idx] = remainder;
idx++;
}
int j, n = 1, k = 0, compare[length];
for(j = 1; j <= length; j++){
compare[k] = n=n>1? n*2:j;
k++;
}
int sum = 0, r = 0;
for(j = length-1; j >= 0; j--){
if(array[j] == 1){
sum += compare[r];
}
r++;
printf("test: %d\n", sum); //<--- test
}
printf("Decimal: %d\n", sum);
}