0

This is my c code that is within the function main:

int numbers[8] = {0,1,1,0,1,0,0,1}; 
int i = 7;
int value = 0;
while (i > -1){
   if (i == 7){
      if (numbers[i] == 1){
         value += 1; 
      }
   } else if (i == 6){
      if (numbers[i] == 1){
           value += 2;
      }
  } else if (i == 5){
      if (numbers[i] == 1){
            value += 4;
      }
  } else if (i == 4){
      if (numbers[i] == 1){
            value += 8;
      }
  } else if (i == 3){
      if (numbers[i] == 1){
             value += 16;
      }
  } else if (i == 2){
      if (numbers[i] == 1){
         value += 32;
      }
 } else if (i == 1){
      if (numbers[i] == 1){
           value += 64;
     }
 } else if (i == 0){
     if (numbers[i] == 1){
         value += 128;
     }
  }
  i--; 
}
printf("%d\n", value); 

Is there a better way to display the decimal number that is within the array numbers? The array numbers represents the decimal value: 105, in binary.

3
  • There's a better way to do everything else in that program, but no, printf("%d") is a perfectly fine way to print the decimal value of a number. Commented Oct 31, 2017 at 23:53
  • I mean more so the way that I loop over the array and count the binary values. It seems like to many if statements. Commented Oct 31, 2017 at 23:54
  • Your instincts there are good...yes, it's too much repetition. Use a switch, or a loop. Commented Oct 31, 2017 at 23:55

2 Answers 2

2
int multiplier = 1;
int value = 0;
for (int i = 7; i >= 0; i--)
{
    value += (numbers[i] * multiplier);
    multiplier *= 2;
}

printf("%d\n", value); 
Sign up to request clarification or add additional context in comments.

Comments

1

You can write a separate function that will convert an array of binary digits to a number. For example

#include <stdio.h>

unsigned long long int array_to_binary(const unsigned int a[], size_t n)
{
    const unsigned long long Base = 2;
    unsigned long long int binary = 0;

    for (size_t i = 0; i < n; i++)
    {
        binary = Base * binary + a[i];
    }

    return binary;
}

int main( void )
{
    unsigned int a[] = { 0, 1, 1, 0, 1, 0, 0, 1 };

    printf("array_to_binary( a, sizeof( a ) / sizeof( *a ) ) = %lld\n",
        array_to_binary(a, sizeof(a) / sizeof(*a)));

    return 0;
}

The program output is

array_to_binary( a, sizeof( a ) / sizeof( *a ) ) = 105

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.