Vahid
Vahid

Reputation: 3442

C#: Write signed byte array ( sbyte[] ) to a File

With File.WriteAllBytes we can write byte array into a file like this:

byte[] myByteArray;
File.WriteAllBytes(@"C:\myFile.format", myByteArray);

But is there a way to write signed byte array ( sbyte[] ) to a file?
Something like this:

sbyte[] my_sByteArray;
File.WriteAllsBytes(@"C:\myFile.format", my_sByteArray);

For those who want to know the reason that why I want this, please follow my question here.

Upvotes: 1

Views: 1927

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149030

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.

Upvotes: 2

Related Questions