I'm trying to convert a binary number to a decimal. In my code, the digits will be inputed as members of an array of integers, then some mathematical operations will be done on each member and finally adding and string the result in another variable. I initially wanted collecting my binary number as a string then converting to an array of int using atoi or strol but I couldn't so I tried this way.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int binToint(int arrName[]);
int binToint(int arrName[]) {
int index;
int length, j, x = 0; //initializing length, x and j to 0
for (index = 0; arrName[index] == 1 || arrName[index] == 0; index++)
++length;
j = length;
for (index = 0; index < length; index++) {
--j;
if (j < 0)
break;
x += arrName[index] * ((int)pow(10, j)); //decimal = binary x 10^index of digit
}
printf("Result: %d", x);
return x;
}
int main(void) {
int tester[] = {1,1,1,0,1,1}; //i used the commas so that each digit will be stored separately
binToint(tester); //calling the function
}
After running, I didn't get any output, rather, I got an empty screen. The output is supposed to be:
Result: 59
I will be glad if my mistakes are spotted and corrected. I will also appreciate optimizations to my code. Thanks
lengtharrName[index] != '\0'-arrNameis an int array, not a zero terminated string.x =+ arrName...should bex += arrName...?length, is not initialized, it's just declared. It's initial content is not determined.int length = 0, j = 0, x = 0;