将 C# 字节转换为 BitArray
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11204666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting C# byte to BitArray
提问by Shamim Hafiz
Is there any predefined function available to convert a byteinto BitArray?
是否有任何预定义的函数可用于将 a 转换byte为BitArray?
One way would be to inspect every bit of the bytevalue and then perform bitwiseoperation. I was wondering if there is any way which is more straightforward than this.
一种方法是检查byte值的每一位,然后执行按位运算。我想知道是否有比这更直接的方法。
采纳答案by CodeCaster
Yes, using the appropriate BitArray()constructoras described here:
是的,使用此处描述的适当BitArray()构造函数:
var bits = new BitArray(arrayOfBytes);
You can call it with new BitArray(new byte[] { yourBite })to create an array of one byte.
您可以调用它new BitArray(new byte[] { yourBite })来创建一个字节的数组。
回答by Jesus Mogollon
if you have a byte number or even an integer, etc.
如果你有一个字节数甚至一个整数等。
BitArray myBA = new BitArray(BitConverter.GetBytes(myNumber).ToArray());
Note: you need a reference to System.Linq
注意:您需要对 System.Linq 的引用
回答by Akbar Jafari
Solution is simple, just two instructions (which are marked in following code), simply convert byte to binary using Convert.ToString(btindx,2), zero pad the resultant string to 8 bits (or lengths 8),strBin.PadLeft(8,'0');and concatenate all binary strings to form a bit stream of your byte array, If you like, you can also form an array of strings to separate each byte's binary representation.
解决方案很简单,只需两条指令(在以下代码中标记),只需使用 将字节转换为二进制Convert.ToString(btindx,2),将结果字符串零填充为 8 位(或长度为 8),strBin.PadLeft(8,'0');并将所有二进制字符串连接起来形成字节的位流数组,如果你愿意,你也可以组成一个字符串数组来分隔每个字节的二进制表示。
byte[] bt = new byte[2] {1,2};
string strBin =string.Empty;
byte btindx = 0;
string strAllbin = string.Empty;
for (int i = 0; i < bt.Length; i++)
{
btindx = bt[i];
strBin = Convert.ToString(btindx,2); // Convert from Byte to Bin
strBin = strBin.PadLeft(8,'0'); // Zero Pad
strAllbin += strBin;
}

