-2

So I'm trying to figure out how I can convert a binary array (of either size of 4 or 8) to a decimal and hexadecimal number in C.

E.g. say you had {0, 0, 0, 1} or {1, 1, 1, 1, 0, 0, 0, 0} and you want to convert to decimal and hexadecimal. I managed to get it working through using the 8 binary array through this link, however my method seems to fall when I try to use it for 4 element.

uint8_t ConvertToDec(uint8_t * bits, uint8_t size)
{
   uint8_t result = 0 ;

   for(uint8_t i=0; i < size-1; i++ ){
       result |=bits[i];
       result<<=1; 
   }   

   return result;

}

int main()
{
    uint8_t bits[] = {1, 1, 1, 1, 0, 0, 0, 0};
    uint8_t len = (sizeof(bits)/sizeof(bits[0]));
    uint8_t result = ConvertToDec(bits,len);
    char hex[5];
    sprintf(hex,"0x%02X",result);
    printf("%s",hex);

    return 0;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Pleas show your code. We can't point out what problems you may have in the code if we can't see it. – kaylum May 23 '20 at 05:35
  • Yes I've made the edit accordingly thank you! – user12345678 May 23 '20 at 05:38
  • Read [*How to debug small programs*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and more about the [C programming language](https://en.cppreference.com/w/c), in particular the [*Modern C*](https://modernc.gforge.inria.fr/) book – Basile Starynkevitch May 23 '20 at 05:49

1 Answers1

1

There are two errors in your code:

  1. The for loop ends one iteration too early. That is, size - 1 should be size.
  2. The left shift should come before masking in the current bit.

So the function should look like:

uint8_t ConvertToDec(uint8_t * bits, uint8_t size)
{
   uint8_t result = 0 ;

   for(uint8_t i=0; i < size; i++ ){
       result<<=1; 
       result |=bits[i];
   }   

   return result;

}
kaylum
  • 13,833
  • 2
  • 22
  • 31