1

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.

Community
  • 1
  • 1
Vahid
  • 3,384
  • 2
  • 35
  • 69

1 Answers1

2

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • But again my_byteArray converts all sbytes to bytes and that is not what I wanted as you can see in the Linked question. – Vahid Jul 19 '13 at 21:53
  • 1
    @Natasha They have the same binary representation. `new sbyte[]{ -2, -1, 0, 1, 2 }` will be written out as `FE FF 00 01 02`. The problem in your linked question, as others pointed out, is not in getting C# to write signed bytes to a file (which this accomplishes), it's in interpreting them when you read it back in Java. – p.s.w.g Jul 19 '13 at 21:59
  • As you can see in comments of the Linked question, how can I use 'cipher.doFinal(myBytes)' in Java? I can't use int[] in Java for the problem. – Vahid Jul 19 '13 at 22:03
  • @Natasha I'm not a Java developer, so sadly, I can't really answer that. This question was specifically about printing signed bytes in C#, and that's what my answer addresses. – p.s.w.g Jul 19 '13 at 22:05
  • @Natasha For what it's worth, I've tried to provide another alternative which might be of some use to you. Hope this helps. – p.s.w.g Jul 19 '13 at 22:11