Search code examples
cconcatenationshift

concatenate array to bits


How can I achieve the following concatenation of 1s and 0s of low the density array data into a smaller more densely filled array c

uint8_t data[16] = {1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1};
uint8_t c[2] = {0};
/*  desired result
    c[0] = 11011011
    c[1] = 10001101 
*/

I am a little bit struggeling here, up to now, I have got it like, but it does not seem to work like I expected:

static void compress(unsigned char *out, unsigned char *in, int length)
{
    for(int i=0; i<length; i++)
    {
        if((i+1)%9==0)
            out++;
        *out |= in[i]<<((length-i)%9);

    }
}  
int main(){
    compress(c,data,16);
    printf("%d",c[0]); //should be 219
    printf("%d",c[1]); //should be 177 (edit)
}

thank you for helping me out!


Solution

  • Add one line to your code printf ("%d %d\n", i,(length-i)%9 ); and you see where the problem is.

    Don't use modulo operation, add variable which helds the bit-shift number (initial value is 7) and reset it when it is negative:

    static void compress2(unsigned char *out, unsigned char *in, int length)
    {
        int shift = 7;
        for(int i=0; i<length; i++)
        {
            *out |= in[i] << shift;
            if (--shift < 0)
            {
                ++out;
                shift = 7;
            }
        }
    }