views:

42

answers:

2

Hi,

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

+4  A: 

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.

Jon Skeet
+3  A: 

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

Steve Townsend
Thanks, but I since need to control exactly which bytes are written, I'll go with `BinaryWriter`.
MartinStettner