英文:
Insert in order a series of bits into a byte (u_int8_t)
问题
将以下变量考虑在内:
u_int8_t newData[BITSTREAM_SIZE/BYTE_SIZE];
bool bits[BITSTREAM_SIZE];
newData 初始化为零,而 bits 数组包含随机的 0 和 1(以单个位的数组形式表示,因为位流是动态的),位流的大小是 8 的倍数或更大。
在对位集进行一些必要的计算后,我需要将位数组转换为字节数组。为了简化起见,我只希望知道需要执行哪些操作,以将 8 位放入一个字节中,按顺序排列(即最重要的位放在开头,最不重要的位放在末尾)。
英文:
consider the following variables
u_int8_t newData[BITSTREAM_SIZE/BYTE_SIZE];
bool bits[BITSTREAM_SIZE];
newData is initialized with zeroes and the array of bits of random ones and zeroes (made as an array of single bits since the stream of bits is dynamic) the bitstream size are equal or greater to multiples of 8.
After some needed calculations with the bitset, i need to convert the array of bits into an array of bytes. For sake of simplicity, i just wish to know what operations are needed to put 8 bits into 1 byte in order (as in most significant bits are place at the beginning and least at the end.)
答案1
得分: 1
// 假设BITSTREAM_SIZE是8的倍数
uint8_t newData[BITSTREAM_SIZE/BYTE_SIZE];
bool bits[BITSTREAM_SIZE];
for (size_t i = 0, j = 0; i < sizeof(newData); ++i)
{
newData[i] = 0;
for (size_t j = 0; j < 8; ++j)
newData[i] = (newData[i] << 1) | (bits[(8 * i) + j] != false);
}
英文:
Try this:
// assumes BITSTREAM_SIZE is a multiple of 8
uint8_t newData[BITSTREAM_SIZE/BYTE_SIZE];
bool bits[BITSTREAM_SIZE];
for (size_t i = 0, j = 0; i < sizeof(newData); ++i)
{
newData[i] = 0;
for (size_t j = 0; j < 8; ++j)
newData[i] = (newData[i] << 1) | (bits[(8 * i) + j] != false);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论