开发者

byte-array as bitfield in C#?

Is there a built-in class or something in .NET that 开发者_如何学运维would allow me to treat a byte-array as a large bitfield?


Take a look at the BitArray class.

Here is an example explaining what is going on when using a byte array:

byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
BitArray myBA3 = new BitArray( myBytes );

Console.WriteLine( "myBA3" );
Console.WriteLine( "   Count:    {0}", myBA3.Count );
Console.WriteLine( "   Length:   {0}", myBA3.Length );
Console.WriteLine( "   Values:" );
PrintValues( myBA3, 8 );

public static void PrintValues( IEnumerable myList, int myWidth )
{
   int i = myWidth;
   foreach ( Object obj in myList )
   {
      if ( i <= 0 )
      {
         i = myWidth;
         Console.WriteLine();
      }
      i--;
      Console.Write( "{0,8}", obj );
   }
   Console.WriteLine();
}

This code produces the following output.

 myBA3
    Count:    40
    Length:   40
    Values:
     Bit0   Bit1    Bit2    Bit3    Bit4    Bit5    Bit6    Bit7
     True   False   False   False   False   False   False   False
     Bit8   Bit9    Bit10   Bit11   Bit12   Bit13   Bit14   Bit15 ... and so on
    False    True   False   False   False   False   False   False
     True    True   False   False   False   False   False   False
    False   False    True   False   False   False   False   False
     True   False    True   False   False   False   False   False
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜