gpt4 book ai didi

c# - 在 C# 中从磁盘读取短数组的最佳方法?

转载 作者:行者123 更新时间:2023-12-02 16:47:12 27 4
gpt4 key购买 nike

我必须将 4GB short[] 数组写入磁盘或从磁盘写入,因此我找到了写入数组的函数,但我正在努力编写代码以从磁盘读取数组。我通常使用其他语言编写代码,所以如果到目前为止我的尝试有点可悲,请原谅我:

using UnityEngine;
using System.Collections;
using System.IO;

public class RWShort : MonoBehaviour {

public static void WriteShortArray(short[] values, string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
foreach (short value in values)
{
bw.Write(value);
}
}
}
} //Above is fine, here is where I am confused:


public static short[] ReadShortArray(string path)
{
byte[] thisByteArray= File.ReadAllBytes(fileName);
short[] thisShortArray= new short[thisByteArray.length/2];
for (int i = 0; i < 10; i+=2)
{
thisShortArray[i]= ? convert from byte array;
}


return thisShortArray;
}
}

最佳答案

shorts是两个字节,所以每次要读入两个字节。我还建议像这样使用 yield return,这样您就不会试图一次性将所有内容都拉入内存。不过,如果您需要将所有短裤放在一起,那对您没有帮助……我想取决于您用它做什么。

void Main()
{
short[] values = new short[] {
1, 999, 200, short.MinValue, short.MaxValue
};

WriteShortArray(values, @"C:\temp\shorts.txt");

foreach (var shortInfile in ReadShortArray(@"C:\temp\shorts.txt"))
{
Console.WriteLine(shortInfile);
}
}

public static void WriteShortArray(short[] values, string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
foreach (short value in values)
{
bw.Write(value);
}
}
}
}

public static IEnumerable<short> ReadShortArray(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(fs))
{
byte[] buffer = new byte[2];
while (br.Read(buffer, 0, 2) > 0)
yield return (short)(buffer[0]|(buffer[1]<<8));
}
}

您也可以这样定义它,利用 BinaryReader:

public static IEnumerable<short> ReadShortArray(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(fs))
{
while (br.BaseStream.Position < br.BaseStream.Length)
yield return br.ReadInt16();
}
}

关于c# - 在 C# 中从磁盘读取短数组的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60083078/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com