Reputation: 255
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
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 sbyte
s, 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
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