-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;
}
3
  • Pleas show your code. We can't point out what problems you may have in the code if we can't see it. Commented May 23, 2020 at 5:35
  • Yes I've made the edit accordingly thank you! Commented May 23, 2020 at 5:38
  • Read How to debug small programs and more about the C programming language, in particular the Modern C book Commented May 23, 2020 at 5:49

1 Answer 1

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;

}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh okay this makes so much more sense. Thank you for your help!!

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.