如何从文件中读取带符号的字节

时间:2014-04-17 09:38:31

标签: c# io

我有一个包含十六进制字的文件。

基本上,我想将文件读入数组sbyte[]

我知道我可以使用

将其读入byte[]
byte[] bt = File.ReadAllBytes("fileName");

但如何将其读入带符号的字节数组? 有人可以给我一些想法吗?

2 个答案:

答案 0 :(得分:3)

你可以只输出字节:

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

或者,如果您希望直接将文件作为sbyte读取,则可以执行以下操作:

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();

答案 1 :(得分:0)

文件有多大?如果它足够小以至于File.ReadAllBytes没问题,你可以这样做:

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

虽然坦率地说:我将其保留为byte[]并担心其他地方签名/未签名。