我得到了以下代码:
byte[] myBytes = new byte[10 * 10000];
for (long i = 0; i < 10000; i++)
{
byte[] a1 = BitConverter.GetBytes(i);
byte[] a2 = BitConverter.GetBytes(true);
byte[] a3 = BitConverter.GetBytes(false);
byte[] rv = new byte[10];
System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);
}
一切正常。我试图转换此代码,以便将所有内容写入 myBytes
但后来我意识到,我使用了 long 并且如果它的值会更高,则 int.MaxValue
转换将失败。
如何解决这个问题?
另一个问题是,因为我不想在内存中创建一个非常大的字节数组,我如何将它直接发送到我的 .WriteBytes(path, myBytes);
函数?
最佳答案
如果如建议的那样,最终目的地是文件:那么更直接地写入文件,而不是在内存中缓冲:
using (var file = File.Create(path)) // or append file FileStream etc
using (var writer = new BinaryWriter(file))
{
for (long i = 0; i < 10000; i++)
{
writer.Write(i);
writer.Write(true);
writer.Write(false);
}
}
也许在您的情况下执行此操作的理想方法是在序列化每个对象时依次将单个 BinaryWriter
实例传递给它们(不要打开和关闭每个对象的文件)。
关于c# - 需要帮助从小字节数组创建大数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12858465/