Converting C# byte to BitArray

久未见 提交于 2019-11-27 23:34:39

问题


Is there any predefined function available to convert a byte into BitArray?

One way would be to inspect every bit of the byte value and then perform bitwise operation. I was wondering if there is any way which is more straightforward than this.


回答1:


Yes, using the appropriate BitArray() constructor as described here:

var bits = new BitArray(arrayOfBytes);

You can call it with new BitArray(new byte[] { yourBite }) to create an array of one byte.




回答2:


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




回答3:


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.

    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;
    }


来源:https://stackoverflow.com/questions/11204666/converting-c-sharp-byte-to-bitarray

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!