问题
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;
}
回答1:
Basically you need to round up the number of bytes needed in your first method:
byte[] ret = new byte[(bits.Length + 7) / 8];
bits.CopyTo(ret, 0);
Your second method already looks okay at first glance... it certainly fills the right number of bytes. It may not fill them in the way you want it to, but in that case you need to provide more detail about how you expect it to be filled. You may want to just change the initial value of bitIndex
for example. (Sample input and output would be immensely useful.)
来源:https://stackoverflow.com/questions/22719893/how-to-convert-bit-array-to-byte-when-bit-array-has-only-5-bits-or-6bits