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 ...
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With