Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write signed byte array to a stream

Tags:

c#

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?

like image 715
Ivan Avatar asked Aug 10 '26 11:08

Ivan


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

like image 104
Jon Skeet Avatar answered Aug 14 '26 19:08

Jon Skeet