在一个字节(u_int8_t)中按顺序插入一系列位。

huangapple go评论61阅读模式
英文:

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 &lt; sizeof(newData); ++i)
{
   newData[i] = 0;
   for (size_t j = 0; j &lt; 8; ++j)
       newData[i] = (newData[i] &lt;&lt; 1) | (bits[(8 * i) + j] != false);
}

huangapple
  • 本文由 发表于 2023年2月16日 06:58:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466213.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定