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