Ivan
Ivan

Reputation: 1171

Write signed byte array to a stream

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?

Upvotes: 2

Views: 1221

Answers (2)

DrKoch
DrKoch

Reputation: 9782

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502016

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

Upvotes: 8

Related Questions