I have already wrote a program to this , bits working only if bit array length is multiples of 8 . Can some one help me to get bit array of 5 bits converted into byte
both functions work only when it have bit array in multiple of 8 .
public static byte[] BitArrayToByteArray(BitArray bits)
{
byte[] ret = new byte[bits.Length / 8];
bits.CopyTo(ret, 0);
return ret;
}
public static byte[] ToByteArray(this BitArray bits)
{
int numBytes = bits.Count / 8;
if (bits.Count % 8 != 0) numBytes++;
byte[] bytes = new byte[numBytes];
int byteIndex = 0, bitIndex = 0;
for (int i = 0; i < bits.Count; i++)
{
if (bits[i])
bytes[byteIndex] |= (byte)(1 << (7 - bitIndex));
bitIndex++;
if (bitIndex == 8)
{
bitIndex = 0;
byteIndex++;
}
}
return bytes;
}