You can actually do this:
sbyte[] my_sByteArray = { -2, -1, 0, 1, 2 };
byte[] my_byteArray = (byte[])my_sByteArray.Cast<byte>();
File.WriteAllBytes(@"C:\myFile.format", my_byteArray); // FE FF 00 01 02
Or even this:
sbyte[] my_sByteArray = { -2, -1, 0, 1, 2 };
byte[] my_byteArray = (byte[])(Array)my_sByteArray;
File.WriteAllBytes(@"C:\myFile.format", my_byteArray); // FE FF 00 01 02
One possible alternative solution is to convert the sbytes
to short
's or int
's before writing them to the file. Like this:
sbyte[] my_sByteArray = { -2, -1, 0, 1, 2 };
byte[] my_byteArray =
my_sByteArray.SelectMany(s => BitConverter.GetBytes((short)s)).ToArray();
File.WriteAllBytes(@"C:\myFile.format", my_byteArray);
// FE FF FF FF 00 00 01 00 02 00
Of course this doubles (or quadruples if using int
) the number of bytes you have to write, for very little benefit.