简体   繁体   中英

byte-array as bitfield in C#?

.NET中是否有内置类或某些东西可以将字节数组视为大位域?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM