简体   繁体   中英

Convert an Array of Ints Representing a Binary Number to a Decimal Number

I have an array of ints that represent a binary number. I need to convert it to its decimal integer equivalent. Can someone please help me?

int octet[8] = {0, 1, 0, 0, 1, 0, 1, 0};

I want to return the decimal equivalent which would be 74 in this case.

This is an example of how you could do something like that:

#include <stdio.h>                                                                                                                                      
                                                                            
int main()                                                                      
{                                                                               
                                                                            
    int octet[] = {0, 1, 0, 0, 1, 0, 1, 0};                                    
    int *p = octet;                                                             
    int len = sizeof(octet) / sizeof(octet[0]); // 8                                                                
    unsigned result = 0;                                                        
                                                                                
    while(len--) result = (result<<1) | *p++;                                   
    /* 74 */                                                                     
    printf("%u\n", result);                                                     
                                                                                
}                   

2^0 x the last element + 2^1 x the second-to-last element + 2^2 x the third-to-last element +...

#include <stdio.h>

int main()                                                                      
{
  // Make array constant and let the compiler tell us how many elements are contained.
  // Doing it this way allows "octet" to grow up to the number of bits in an integer elements.  
  // It won't be an "octet" anymore though,...
  const int octet[] = {0, 1, 0, 0, 1, 0, 1, 0};         
  const int NumArrayElements = sizeof(octet) / sizeof(*octet);

  // Assign hi bit to save a loop iteration.
  int value = octet[0];
  
  // Run remaining bits, shifting up and or-ing in new values.
  for(int i=1; i<NumArrayElements; i++)
  {
    value <<= 1;
    value |= octet[i];
  }
  
  printf("%d\n", value);
}

This is a simple thing to do, but having the compiler handle some of the sizing issues and adding comments makes it much easier to maintain over time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM