2

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?

1
  • simply cast sbyte to byte. It is the same bits anyway. Commented Aug 6, 2015 at 10:50

2 Answers 2

8

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".

Sign up to request clarification or add additional context in comments.

7 Comments

Why not byte[] e = (byte[])data?
@DrKoch: Because it wouldn't compile. I've added an extra paragraph to explain that.
thank you. but is 'equivalentData' going to be signed?
@Ivan: I don't know what you mean by that. It's a reference with a compile-time type of 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...
@Ivan: If you think of signed bytes as merely an interpretation of the underlying (unsigned) bytes, it will make sense. In the same way that 4 bytes can be interpreted as an integer, or as a float, or something else encoded as 4 bytes; you can interpret a single byte as a signed byte by interpreting the bits in the byte differently. You can not send "signed bytes", you always send (unsigned) bytes.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.