C# 字节[]到位数组并返回到字节[]
正如标题所述,我正在尝试再次将字节数组转换为位数组,再转换为字节数组 我知道C# 字节[]到位数组并返回到字节[],c#,.net,visual-studio,C#,.net,Visual Studio,正如标题所述,我正在尝试再次将字节数组转换为位数组,再转换为字节数组 我知道Array.CopyTo()解决了这个问题,但是由于BitArray在LSB中存储值的方式,接收到的字节数组与原始数组不同 你在C中是怎么做的?这应该可以 static byte[] ConvertToByte(BitArray bits) { // Make sure we have enough space allocated even when number of bits is not a multipl
Array.CopyTo()
解决了这个问题,但是由于BitArray在LSB中存储值的方式,接收到的字节数组与原始数组不同
你在C中是怎么做的?这应该可以
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对其进行验证。因此,我提供了测试用例来确认结果以获得字节[]
的位数组
,您只需使用位数组的构造函数
:
BitArray bits = new BitArray(bytes);
要获取位数组的字节[]
,有许多可能的解决方案。我认为一个非常优雅的解决方案是使用BitArray.CopyTo
方法。只需创建一个新阵列并将位复制到:
byte[]resultBytes = new byte[(bits.Length - 1) / 8 + 1];
bits.CopyTo(resultBytes, 0);
你可以做smth。就像整数除法和+1一样,这比仅仅使用天花板更清晰吗?@Mardoxx肯定!这是一个很常见的成语。我想它也更正确!不用去int->real->int谢谢你的回答!我太粗心了,因为我正在处理一个非常大的数据集,所以在尝试之前就假设它不起作用;改用:var bytes=new byte[(int)Math.天花((double)bits.Length/8)];