如何从文件中读取符号字节(How to read signed bytes from a file)

2019-10-19 22:01发布

我得到的十六进制字行的文件。

基本上,我希望将文件读入一个数组sbyte[]

我大概知道我可以读入一个byte[]使用

byte[] bt = File.ReadAllBytes("fileName");

但如何读入一个符号字节数组? 可能有人给我一些想法?

Answer 1:

该文件有多大? 如果它足够小File.ReadAllBytes是好的,你可能只是做:

byte[] bt = File.ReadAllBytes("fileName");
sbyte[] sbt = new sbyte[bt.Length];
Buffer.BlockCopy(bt, 0, sbt, 0, bt.Length);

尽管坦率地说:我会保持它作为一个byte[]和担心符号/无符号的其他地方。



Answer 2:

You can just cast the bytes:

byte[] bt = File.ReadAllBytes("fileName");
sbyte[] sbytes = Array.ConvertAll(bt, b => (sbyte)b);

Or if you prefer to read the file directly as sbytes, you can do something like that:

static IEnumerable<sbyte> ReadSBytes(string path)
{
    using (var stream = File.OpenRead(path))
    using (var reader = new BinaryReader(stream))
    {
        while (true)
        {
            sbyte sb;
            try
            {
                sb = reader.ReadSByte();
            }
            catch(EndOfStreamException)
            {
                break;
            }
            yield return sb;
        }
    }
}

sbyte[] sbytes = ReadSBytes("fileName").ToArray();


文章来源: How to read signed bytes from a file
标签: c# io