Arbitrary data type of bit size in C #

What is the best way to define in C # a structure with, say, 6 data bits? I can of course define 2 int + short fields, but I wonder if there is a way to save all the data in 1 file.

+5
source share
5 answers

BitVector32 was designed with bit packing in mind (of course, the structure you want to keep must match 32 bits).

See here and here for some examples.

+4
source

The BitArray class is used for this purpose. This is in System.Collections

http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx

+2

6 , a byte , , 8 .

public struct SixBits {

  private byte _data;

  private SixBits(byte value) {
    _data = value;
  }

  public SixBits ChangeBit(int index, bool value) {
    if (index < 0 || index > 5) throw new IndexOutOfRangeException();
    return new SixBits((byte)(_data & ~(1 << index) | ((value ? 1 : 0) << index)));
  }

  public bool this[int index] {
    get {
      if (index < 0 || index > 5) throw new IndexOutOfRangeException();
      return ((_data >> index) & 1) != 0;
    }
  }

}

6 , a long , , 8 .

public struct SixBytes {

  private long _data;

  private SixBytes(long value) {
    _data = value;
  }

  public SixBytes ChangeByte(int index, byte value) {
    if (index < 0 || index > 5) throw new IndexOutOfRangeException();
    return new SixBytes(_data & ~(0xFFL << (index * 8)) | (long)value << (index * 8));
  }

  public byte this[int index] {
    get {
      if (index < 0 || index > 5) throw new IndexOutOfRangeException();
      return (byte)(_data >> (index * 8));
    }
  }

}

Unit test :

SixBits x = new SixBits();
for (int i = 0; i < 6; i++) Assert.AreEqual(false, x[i]);
for (int i = 0; i < 6; i++) x = x.ChangeBit(i, true);
for (int i = 0; i < 6; i++) Assert.AreEqual(true, x[i]);
for (int i = 0; i < 6; i++) x = x.ChangeBit(i, false);
for (int i = 0; i < 6; i++) Assert.AreEqual(false, x[i]);
for (int i = 0; i < 6; i++) x = x.ChangeBit(i, (i & 1) == 0);
for (int i = 0; i < 6; i++) Assert.AreEqual((i & 1) == 0, x[i]);
for (int i = 0; i < 6; i++) x = x.ChangeBit(i, (i & 1) == 1);
for (int i = 0; i < 6; i++) Assert.AreEqual((i & 1) == 1, x[i]);

SixBytes y = new SixBytes();
for (int i = 0; i < 256; i++) {
  for (int j = 0; j < 6; j++) y = y.ChangeByte(j, (byte)i);
  for (int j = 0; j < 6; j++) Assert.AreEqual((byte)i, y[j]);
}
byte[] test = { 0, 1, 64, 2, 255, 3, 14, 32, 4, 96, 6, 254, 7, 12, 255, 128, 127 };
for (int i = 0; i < test.Length - 6; i++) {
  for (int j=0;j<6;j++) y = y.ChangeByte(j, test[i+j]);
  for (int j=0;j<6;j++) Assert.AreEqual(test[i+j], y[j]);
}
+2

BitArray (System.Collections.BitArray)?

- int + short ... 32 ( int).

- - .

0

, 6 . (int plus short - 6 ).

, , , .

- , - 128 , - 64. , , , ( ).

0

All Articles