gpt4 book ai didi

将数组连接到位

转载 作者:行者123 更新时间:2023-11-30 18:27:51 25 4
gpt4 key购买 nike

如何将低密度数组 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com