正如标题所述,我正在尝试再次将字节数组转换为位数组,再转换回字节数组。
我知道Array.CopyTo()会处理这个问题,但由于BitArray在LSB中存储值的方式不同,接收到的字节数组与原始字节数组不同。
在C#中你是怎么做的呢?
发布于 2017-08-18 23:24:52
这应该就行了
static byte[] ConvertToByte(BitArray bits) {
// Make sure we have enough space allocated even when number of bits is not a multiple of 8
var bytes = new byte[(bits.Length - 1) / 8 + 1];
bits.CopyTo(bytes, 0);
return bytes;
}你可以使用一个简单的驱动程序来验证它,如下所示
// test to make sure it works
static void Main(string[] args) {
var bytes = new byte[] { 10, 12, 200, 255, 0 };
var bits = new BitArray(bytes);
var newBytes = ConvertToByte(bits);
if (bytes.SequenceEqual(newBytes))
Console.WriteLine("Successfully converted byte[] to bits and then back to byte[]");
else
Console.WriteLine("Conversion Problem");
}我知道OP知道Array.CopyTo解决方案(与我这里的解决方案类似),但我不明白它为什么会导致任何位顺序问题。仅供参考,我正在使用.NET 4.5.2进行验证。因此,我提供了测试用例来确认结果。
https://stackoverflow.com/questions/45759398
复制相似问题