简体   繁体   中英

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM