首页 > 解决方案 > 如何将 8 位无符号整数数组打包成 11 位无符号整数数组

问题描述

想象一下 C 提供无符号整数类型,比如 uint11_t 大小为 11 位。我想将一个 8 位无符号整数数组打包成 11 位无符号整数数组。

uint8_t in_array[100];    // 8 x 100 = 800 bits
uint11_t out_array[73];   // 11 x 73 = 803 bits enough to pack 800 bits from in_array

这本质上是滑动窗口问题,其中 11 位的窗口要在 8 位字上滑动。

如何在不依赖结构、联合或 memcpy 的情况下使用 C 中的位操作操作、数组缓冲区和循环来做到这一点?

标签: arrayscbit-manipulation

解决方案


一次读取 8 位累加器。
当其中有 11 位或更多位时,取出 11 位并保存。

如果重新打包假设低地址 8 位字节成为最高或最低有效位,则采用不同的方法。下面假设它们是最不重要的。

uint8_t in_array[100];
uint11_t out_array[73];

unsigned out_index = 0;
unsigned accumulator = 0;
unsigned bits = 0;
for (unsigned in_index = 0; in_index < 100; in_index++) {
  accumulator |= ((unsigned) in_array[in_index]) << bits;
  bits += 8;
  if (bits >= 11) {
    out_array[out_index++] = accumulator & 0x3FF;  // 11 LSBits
    accumulator >>= 11;
    bits -= 11;
  }
}
if (bits > 0) {
  // TBD code for OP
}

推荐阅读