将零件数组转换为一个字节数组
我想将值为1s和0s的位阵列(bool* bitarray)转换为一个字节数组(无符号char* bytearray),其中每个索引处的值将是一个字节。 对于ex,索引0〜7在bitarray中将进入bytearray [1]。
我该怎么做?假设我已经有一系列位(但是金额可能会根据传入数据的变化)。 我并不担心将其排出8,因为我只会在Bitarray结束时添加填充物,以使其可将其排除在8。
I want to convert an array of bits (bool* bitArray) where the values are 1s and 0s into an array of bytes (unsigned char* byteArray) where the values at each index would be one byte.
For ex, index 0~7 in bitArray would go into byteArray[1].
How would I go about doing this? Assuming that I already have an array of bits (but the amount would be subject to change based on the incoming data).
I am not worried about having it divisible by 8 because I will just add padding at the end of the bitArray to make it divisible by 8.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用位移动或查找数组,然后将数字与1位组合在一起,每个设置一个位于钻头或一次进行8位
。以下数组,如果您认为更简单地理解:
Just just use bit shifts or a lookup array and and combine numbers with 1 bit set each with bitwise or for 8 bits at a time:
The rhs of the
|=
operator could also be replaced with a lookup in the following array, if you consider this simpler to understand:您应该使用
std :: bitset
用于一系列布尔,或者std :: vector< bool>
(如果是动态尺寸)。和std :: Array
用于数组或再次std :: vector
动态大小。我只在下面进行了静态大小,然后转换为和转换。转换涉及应该是一个应该是纪念物的东西(在Little Endian或Unsigned Char类型上)的许多位变化和循环。 -O2的编译器输出不良。 -o3删除循环,to_array2变得有趣。 GCC几乎设法优化了它,Clang实际上将其降低到
movzx eax,word ptr [rdi]
: https://godbolt.org/z/4chb8o81eYou should be using
std::bitset
for an array of bools, orstd::vector<bool>
if it's dynamically sized. Andstd::array
for the array or againstd::vector
for dynamic size. I've only done static size below and conversion to and from.Converting involves a lot of bit shifts and loops for something that should be a memcpy (on little endian or unsigned char types). The compiler output for -O2 is bad. -O3 removes the loop and to_array2 gets interesting. gcc nearly manages to optimize it, clang actually gets it down to
movzx eax, word ptr [rdi]
: https://godbolt.org/z/4chb8o81e