arrays - 如何将 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 中的位操作操作、数组缓冲区和循环来做到这一点?
解决方案
一次读取 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
}
推荐阅读
- java - 为什么要再次将数组转换为列表到数组
- css - 根据值设置材质 ui 表格单元格
- python-3.x - 如何始终使用 python 下载最新版本的 phpmyadmin?
- python - Odoo:动态设置未存储的字段
- pandas - 使用 pandas 合并基于两个条件合并两列
- replace - 如何在 Xamarin.Android 中单击按钮时将一个片段替换为另一个片段?
- python - 使用 python 从深度 2D 图像到 3D 点云
- python - 如何使用 Python 检测有向图中的循环?
- sql - 在 CASE 表达式 Oracle SQL 中将字符串转换为日期
- python - Newspaper3k 返回无摘要