将数组连接到位

标签 c concatenation shift

如何将低密度数组 data 的 1 和 0 串联成更小、更密集填充的数组 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 
*/

我在这里有点挣扎,到目前为止,我已经得到了它,但它似乎没有像我预期的那样工作:

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)
}

谢谢你帮助我!

最佳答案

static void compress(uint8_t *out, uint8_t *in, size_t length)
{
    memset(out, 0, length >> 3 + !!(length & 7));
    for(size_t i = 0; i < length; i++)
    {
        out[i >> 3] |= (in[i] << (7 - (i & 7)));
        //out[i >> 3] |= ((!!in[i]) << (7 - (i & 7)));  - if array elements may be not only 0 or 1.
    }
}  

int main()
{
    uint8_t data[16] = {1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1};
    uint8_t c[sizeof(data) >> 3 + !!(sizeof(data) & 7)];

    compress(c,data,16);
    printf("%d\n",c[0]); //should be 219
    printf("%d\n",c[1]); //should be 141
}

关于将数组连接到位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52344122/

相关文章:

c - 在 C 中使用异构数组

audio - FFmpeg:连接 .webm 文件有些是视频只有一些音频只有一些两者都有

c++ - 在循环中连接 Visual Studio C++ 6.0 中的字符串

c - 在 C 中将常量添加到变量名

java - 移动数组中的元素

C UDP套接字: Arbitrary setsockopt behavior (with SO_RCVTIMEO)

c - 将结构体写入缓冲区

在 C 中编译数据流?

python - 如何计算 Python Pandas 中组的移位列

python - 将列按名称 move 到 pandas 中的表前面