从BitArray转换为Byte

时间:2009-02-18 07:13:49

标签: c# .net binary bitarray base-class-library

我有BitArray,长度为8,我需要一个函数将其转换为byte。怎么做?

具体来说,我需要ConvertToByte的正确功能:

BitArray bit = new BitArray(new bool[]
{
    false, false, false, false,
    false, false, false, true
});

//How to write ConvertToByte
byte myByte = ConvertToByte(bit);
var recoveredBit = new BitArray(new[] { myByte });
Assert.AreEqual(bit, recoveredBit);

10 个答案:

答案 0 :(得分:48)

这应该有效:

byte ConvertToByte(BitArray bits)
{
    if (bits.Count != 8)
    {
        throw new ArgumentException("bits");
    }
    byte[] bytes = new byte[1];
    bits.CopyTo(bytes, 0);
    return bytes[0];
}

答案 1 :(得分:33)

有点晚了,但这对我有用:

public static byte[] BitArrayToByteArray(BitArray bits)
{
    byte[] ret = new byte[(bits.Length - 1) / 8 + 1];
    bits.CopyTo(ret, 0);
    return ret;
}

适用于:

string text = "Test";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(text);
BitArray bits = new BitArray(bytes);
bytes[] bytesBack = BitArrayToByteArray(bits);
string textBack = System.Text.Encoding.ASCII.GetString(bytesBack);
// bytes == bytesBack
// text = textBack

答案 2 :(得分:5)

穷人的解决方案:

protected byte ConvertToByte(BitArray bits)
{
    if (bits.Count != 8)
    {
        throw new ArgumentException("illegal number of bits");
    }

    byte b = 0;
    if (bits.Get(7)) b++;
    if (bits.Get(6)) b += 2;
    if (bits.Get(5)) b += 4;
    if (bits.Get(4)) b += 8;
    if (bits.Get(3)) b += 16;
    if (bits.Get(2)) b += 32;
    if (bits.Get(1)) b += 64;
    if (bits.Get(0)) b += 128;
    return b;
}

答案 3 :(得分:4)

这应该可以解决问题。然而,之前的答案很可能是更好的选择。

    public byte ConvertToByte(BitArray bits)
    {
        if (bits.Count > 8)
            throw new ArgumentException("ConvertToByte can only work with a BitArray containing a maximum of 8 values");

        byte result = 0;

        for (byte i = 0; i < bits.Count; i++)
        {
            if (bits[i])
                result |= (byte)(1 << i);
        }

        return result;
    }

在您发布的示例中,结果字节将为0x80。换句话说,BitArray中的第一个值与返回字节中的第一个位相对应。

答案 4 :(得分:2)

那应该是最终的。可以使用任何长度的数组。

private List<byte> BoolList2ByteList(List<bool> values)
    {

        List<byte> ret = new List<byte>();
        int count = 0;
        byte currentByte = 0;

        foreach (bool b in values) 
        {

            if (b) currentByte |= (byte)(1 << count);
            count++;
            if (count == 7) { ret.Add(currentByte); currentByte = 0; count = 0; };              

        }

        if (count < 7) ret.Add(currentByte);

        return ret;

    }

答案 5 :(得分:1)

除了@JonSkeet的答案,你可以使用Generic Method作为打击:

public static byte ToByte(this BitArray bits)
        {
            if (bits.Count != 8)
            {
                throw new ArgumentException("bits");
            }
            byte[] bytes = new byte[1];
            bits.CopyTo(bytes, 0);
            return bytes[0];
        }

并使用如下:

BitArray foo = new BitArray(new bool[]
{
    false, false, false, false,false, false, false, true
});

foo.ToByte();

答案 6 :(得分:1)

不幸的是,BitArray类部分在.Net Core类(UWP)中实现。例如,BitArray类无法调用CopyTo()和Count()方法。我写了这个扩展来填补空白:

map(Character::getNumericValue)

该方法使用LSB(Less Significant Byte)逻辑将BitArray解码为字节数组。这与BitArray类使用的逻辑相同。调用MSB参数设置为true的方法将产生MSB解码的字节序列。在这种情况下,请记住您可能还需要反转最终输出字节集合。

答案 7 :(得分:0)

byte GetByte(BitArray input)
{
  int len = input.Length;
  if (len > 8)
    len = 8;
  int output = 0;
  for (int i = 0; i < len; i++)
    if (input.Get(i))
      output += (1 << (len - 1 - i)); //this part depends on your system (Big/Little)
      //output += (1 << i); //depends on system
  return (byte)output;
}

干杯!

答案 8 :(得分:0)

小端字节数组转换器:BitArray中的第一位(用&#34; 0&#34;索引) 假设代表最低有效位(位 - 八位字节中最右边的位),它被解释为&#34;零&#34;或者&#34;一个&#34;作为二进制。

 public static class BitArrayExtender {

    public static byte[] ToByteArray( this BitArray bits ) {

        const int BYTE = 8;
        int length = ( bits.Count / BYTE ) + ( (bits.Count % BYTE == 0) ? 0 : 1 );
        var bytes  = new byte[ length ];

        for ( int i = 0; i < bits.Length; i++ ) {

           int bitIndex  = i % BYTE;
           int byteIndex = i / BYTE;

           int mask = (bits[ i ] ? 1 : 0) << bitIndex;
           bytes[ byteIndex ] |= (byte)mask;

        }//for

        return bytes;

    }//ToByteArray

 }//class

答案 9 :(得分:0)

我的代码中的示例:

Public Shared Function BytesXor(a1 As Byte(), a2 As Byte()) As Byte()
    Dim ba1 As BitArray = New BitArray(a1)
    Dim ba2 As BitArray = New BitArray(a2)
    Dim intLength As Integer = System.Math.Min(a1.Length, a2.Length)
    Dim RetrunValue(intLength - 1) As Byte
    If ba1.Length > ba2.Length Then ba1.Length = ba2.Length
    If ba2.Length > ba1.Length Then ba2.Length = ba1.Length
    Dim ba3 As BitArray = ba1.Xor(ba2)
    Dim p As Integer = 0
    For i As Integer = 0 To intLength - 1
        Dim v As Integer = 0
        For j As Integer = 0 To 7
            If ba3.Get(p) Then
                'BitArray(Byte()) sorts bits from lower to higher
                '"BitArray to Byte" must be put by reverse order
                v += 1 << j
            End If
            p += 1
        Next
        RetrunValue(i) = CByte(v)
    Next
    Return RetrunValue
End Function