I want to write signed byte array sbyte[] to a stream. I know that Stream.Write accepts only unsigned byte[], so I could convert sbyte[] to byte[] prior to passing it to the stream. But I really need to send the data as sbyte[]. Is there some way to do it? I found BinaryWriter.Write but is this equivalent to Stream.Write?
-
simply cast sbyte to byte. It is the same bits anyway.DrKoch– DrKoch2015-08-06 10:50:12 +00:00Commented Aug 6, 2015 at 10:50
2 Answers
You can use the fact that the CLR allows you to convert between byte[] and sbyte[] "for free" even though C# doesn't:
sbyte[] data = ...;
byte[] equivalentData = (byte[]) (object) data;
// Then write equivalentData to the stream
Note that the cast to object is required first to "persuade" the C# compiler that the cast to byte[] might work. (The C# language believes that the two array types are completely incompatible.)
That way you don't need to create a copy of all the data - you're still passing the same reference to Stream.Write, it's just a matter of changing the "reference type".
7 Comments
byte[] e = (byte[])data?byte[]. Its execution time value is a reference to the same array as data, representing the same bits in different ways. For example, if you say equivalentData[0] = 255; then data[0] will be -1...Some Background:
An unsigned Byte has 8 Bits and can represent values between 0 and 255.
A signed Byte is the same 8 Bits but interpreted differently: the leftmost Bit (MSB) is considered a "sign" Bit with 0 meaning positive, 1 meaning negative. The remaining 7 Bites may represent a value between 0 and 127.
Combined a unsigned Byte may represent a value between -128 and +127
If you send such a byte over the wire (the network) it is up to the receiver to interpret it correctly.