-2

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

12
  • 3
    you haven't initialized length Commented Feb 8, 2023 at 12:43
  • 3
    arrName[index] != '\0' - arrName is an int array, not a zero terminated string. Commented Feb 8, 2023 at 12:44
  • 1
    x =+ arrName... should be x += arrName... ? Commented Feb 8, 2023 at 12:44
  • 2
    @AbdurrahmanMuhammadKabir, no length, is not initialized, it's just declared. It's initial content is not determined. Commented Feb 8, 2023 at 12:58
  • 2
    Each variable must be individually initialized. int length = 0, j = 0, x = 0; Commented Feb 8, 2023 at 13:02

3 Answers 3

1

As others have said, you cannot calculate the length of an array from inside a function. The length must be passed to the function.

I added a new parameter, len.

After that, calculating the value with bit-shifting is trivially easy.

#include <stdio.h>

int binToint(int bits[const], int len)
{
    int answer = 0;
    for(int i=0; i<len; ++i)
    {
        answer = (answer << 1) + bits[i];
    }
    return answer;
}

int main(void) {

  int tester[] = {1,1,1,0,1,1};
  int result = binToint(tester, 6); //calling the function, including the length.
  
  printf("Result is %d\n", result);
}

Output

Result is 59
Sign up to request clarification or add additional context in comments.

4 Comments

Interesting to mix <<, +. I'd expect arithmetic *, + or logical <<, |. But likely compiler will emit efficient code for all 3.
@chux: It seems that you comment on virtually all of my answers. Sometimes insightfully, and sometimes with minor points.
please why did you use the pre increment operator ++i instead of post increment i++, i'm confused
@AbdurrahmanMuhammadKabir: It really does not matter. I learned pre-increment, and use it by habit. I understand that most people have been taught post-increment, and use it too. But it does not matter which one is used here.
1

Remember that any number is just the coefficients of a polynomial for each power of the radix (or base). That is:

      3×102  +  0×101  +  7×100    ==     3 0 7    ==     307

For binary the radix is not 10, but 2. So:

      1 0 1 12    ==     1×23 + 0×22 + 1×21 + 1×20
      ⟶     8 + 0 + 2 + 1    ==     1110

The neat trick is that all this “power of” stuff is just repeated multiplication, so it is very easy to build a number up by just starting with the leftmost (most-significant) digit, and then multiplying by the radix each time before adding the next digit value:

multiply,    add
0 * 2 =  0,  0 + [1] (first digit)  = 1
1 * 2 =  2,  2 + [0] (second digit) = 2
2 * 2 =  4,  4 + [1] (third digit)  = 5
5 * 2 = 10, 10 + [1] (fourth digit) = 11 (final answer)

When you are given an array of binary values (0 or 1, not '0' or '1') you can easily build up your result. Start with 0 and simply multiply and add for each next digit:

int value = 0;
for (each digit in the input array, left to right)
{
  value *= 2;
  value += digit;
}
return value;

Going backwards (int to array) is only complicated by the fact that you can only peel digits off from the right (least-significant), but is otherwise just as simple.

Good luck!

Comments

1

Code risks running off the end of the array.

With

int tester[] = {1,1,1,0,1,1};
binToint(tester);

And with int binToint(int arrName[])

for (index = 0; arrName[index] == 1 || arrName[index] == 0; index++)

nothing is to certainly stop arrName[index] from going past arrName[5].

Code should pass in a length.

int tester[] = {1,1,1,0,1,1};
int n = sizeof tester/sizeof tester[0];
binToint(n, tester);

And then iterate:

int binToint(int n, int arrName[]) {
  ...
  for (index = 0; index < n; index++)

Bad initialization

Only x in initialized.

// int length, j, x = 0;
int length = 0;
int j = 0;
int x = 0;

No overflow detection

Robust code would complain about trying to form a value more than INT_MAX.

Code may have other issues too

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.