Directly from a Byte Array, your quickest solution is probably using a BitArray.
- http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx
E.g. This would go something like:
public void BitManimulation()
{
//Ill just use 2 bytes here for demonstration, get your 16 bytes here.
byte[] bytes = new[] { (byte)250, (byte)250 };
//Convert your bytes to a BitArray.
BitArray array = new BitArray(bytes);
array[3] = !array[3]; // Flip
array[4] = false; // 0
array[5] = true; // 1
//Convert back to bytes.
byte[] bytes2 = new byte[2];
array.CopyTo(bytes2,0);
Console.WriteLine(bytes2[0]);
Console.WriteLine(bytes2[1]);
}
Now this comes with a performance penalty.
So as an alternative you have the BitVector32 that will require you to convert blocks of 4 bytes to an integer...
- http://msdn.microsoft.com/en-us/library/system.collections.specialized.bitvector32.aspx
Finally you can do bit shifting, XOR's etc to produce the desired results. Since @dasblinkenlight already left a nice answer for that ill just leave you with that for explaining things.^
Here is some quick helper methods based on his post though:
public static class ByteArrayExt
{
public static byte[] SetBit(this byte[] self, int index, bool value)
{
int byteIndex = index / 8;
int bitIndex = index % 8;
byte mask = (byte)(1 << bitIndex);
self[byteIndex] = (byte)(value ? (self[byteIndex] | mask) : (self[byteIndex] & ~mask));
return self;
}
public static byte[] ToggleBit(this byte[] self, int index)
{
int byteIndex = index / 8;
int bitIndex = index % 8;
byte mask = (byte)(1 << bitIndex);
self[byteIndex] ^= mask;
return self;
}
public static bool GetBit(this byte[] self, int index)
{
int byteIndex = index / 8;
int bitIndex = index % 8;
byte mask = (byte)(1 << bitIndex);
return (self[byteIndex] & mask) != 0;
}
}