unsigned char array of 8 bits to unsigned char

2k views Asked by At

I've created a function that turns an unsigned char into an unsigned char array of size 8 (where each index contains either 0 or 1, making up the 8 bits of the given char). Here is the 100% working version:

unsigned char * ucharToBitArray(unsigned char c)
{
   unsigned char * bits = malloc(8);

   int i;
   for(i=sizeof(unsigned char)*8; i; c>>=1)
       bits[--i] = '0'+(c&1);

   return bits ;
}

I need to create a function that does the exact opposite of this now. Meaning, it will take and unsigned char array of size 8, and turn it into a regular single unsigned char. What is an effective way of doing so?

Thanks for the help!

1

There are 1 answers

0
Lundin On BEST ANSWER

The function is needlessly complex and obscure. I would suggest replacing it with this:

void ucharToBitArray(char bits[8], uint8_t c)
{
   for(uint8_t i=0; i<8; i++)
   {
     if(c & (1<<i))
     {
       bits[7-i] = '1';
     }
     else
     {
       bits[7-i] = '0';
     }
   }
}

Now to convert it back, simply go the other way around. Check bits[i] and then set c |= (1<<i) if you found a '1'.