user3535716
user3535716

Reputation: 255

How to read signed bytes from a file

I got a file with lines of hex words.

Basically, I want to read the file into an array sbyte[].

I know probably I can read it into a byte[] using

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

But how to read it into a signed byte array? Could somebody give me some ideas?

Upvotes: 1

Views: 2283

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292545

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

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1063318

How big is the file? If it is small enough that File.ReadAllBytes is fine, you can probably just do:

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

Although frankly: I'd keep it as a byte[] and worry about signed/unsigned elsewhere.

Upvotes: 0

Related Questions