将BitArray转换为小字节数组 [英] Convert BitArray to a small byte array
问题描述
我已经阅读了有关BitArray转换的其他文章,并亲自尝试了几次,但似乎都没有提供想要的结果.
I've read the other posts on BitArray conversions and tried several myself but none seem to deliver the results I want.
我的情况就是这样,我有一些控制LED灯条的c#代码.要向测试条发出单个命令,我最多需要28位
My situation is as such, I have some c# code that controls an LED strip. To issue a single command to the strip I need at most 28 bits
1位用于在2条LED灯条之间进行选择
1 bit for selecting between 2 led strips
6个位置(最多48个可寻址LED)
6 for position (Max 48 addressable leds)
颜色x3为7(颜色值为0-127)
7 for color x3 (0-127 value for color)
假设我为该结构创建一个BitArray,作为示例,我们将其随机填充.
Suppose I create a BitArray for that structure and as an example we populate it semi-randomly.
BitArray ba = new BitArray(28);
for(int i = 0 ;i < 28; i++)
{
if (i % 3 == 0)
ba.Set(i, true);
else
ba.Set(i, false);
}
现在,我想将这28位保留在4个字节中(最后4位可以是一个停止信号),最后将其转换为字符串,这样我就可以通过USB将字符串发送到LED灯条.
Now I want to stick those 28 bits in 4 bytes (The last 4 bits can be a stop signal), and finally turn it into a String so I can send the string via USB to the LED strip.
我尝试过的所有方法都将1和0转换为文字字符,这不是目标.
All the methods I've tried convert each 1 and 0 as a literal char which is not the goal.
在C#中是否有一种直接的方法来进行位压缩?
Is there a straightforward way to do this bit compacting in C#?
推荐答案
Well you could use BitArray.CopyTo
:
byte[] bytes = new byte[4];
ba.CopyTo(bytes, 0);
或者:
int[] ints = new int[1];
ba.CopyTo(ints, 0);
目前尚不清楚您想要的 string 表示形式是什么-您正在处理的是自然的二进制数据,而不是文本数据...
It's not clear what you'd want the string representation to be though - you're dealing with naturally binary data rather than text data...
这篇关于将BitArray转换为小字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!