Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write Int array to Stream in .NET

what's the best way to write the binary representation of an int array (Int32[]) to a Stream?

Stream.Write only accepts byte[] as source and I would like to avoid converting/copying the array to an byte[] (array but instead streaming directly from the 'original location').

In a more system-oriented language (a.k.a. C++) I would simply cast the int array to a byte* but as far as I understood this isn't possible with C# (and moreover, casting byte* to byte[] wouldn't work out either way)

Thanks

Martin

PS: Actually, I would also like to stream single int values. Does using BinaryConverter.GetBytes() create a new byte array? In this case I extend my question to how to efficiently stream single int values ...

like image 684
MartinStettner Avatar asked Sep 06 '10 13:09

MartinStettner


2 Answers

The simplest option would be to use BinaryWriter wrapping your output stream, and call Write(int) for each of your int values. If that doesn't use the right endianness for you, you could use EndianBinaryWriter from my MiscUtil library.

I don't know of anything built-in to do this more efficiently... I'd hope that the buffering within the stream would take care of it for the most part.

like image 67
Jon Skeet Avatar answered Nov 18 '22 13:11

Jon Skeet


System.Array and System.Int32 both have the SerializableAttribute and so both support default serialization in a retrievable format.

http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx

There is sample code for Binary output and readback here:

http://msdn.microsoft.com/en-us/library/aa904194(VS.71).aspx

like image 40
Steve Townsend Avatar answered Nov 18 '22 14:11

Steve Townsend