-3

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!

David Baez
  • 1,208
  • 1
  • 14
  • 26
  • reverse the operations. essentially `c<<=1;c|=b[i++]-'0'` – AShelly Dec 02 '14 at 04:11
  • Where did you get stuck? – mafso Dec 02 '14 at 06:46
  • `sizeof(char)` is always 1, you need `i = CHAR_BIT` – phuclv Dec 02 '14 at 07:23
  • Or... you could just boldly type out 8 in the code and then hang yourself the day you encounter a system where one byte doesn't have 8 bits. – Lundin Dec 02 '14 at 07:38
  • @David Baez: Note: malloc is returning memory in Byte size. So you aren't really converting an array of 8 bits. you are converting a array of 64 bits, where each byte is representing a bit. To directly convert the bits, you had to use `bit fields` – dhein Dec 02 '14 at 07:47

1 Answers1

1

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'.

Lundin
  • 195,001
  • 40
  • 254
  • 396