Write Int array to Stream in .NET
Solution 1
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.
Solution 2
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
MartinStettner
Self-employed software developer and consultant for software engineering
Updated on June 25, 2022Comments
-
MartinStettner almost 2 years
what's the best way to write the binary representation of an int array (
Int32[]
) to aStream
?Stream.Write
only acceptsbyte[]
as source and I would like to avoid converting/copying the array to anbyte[]
(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, castingbyte*
tobyte[]
wouldn't work out either way)Thanks
Martin
PS: Actually, I would also like to stream single
int
values. Does usingBinaryConverter.GetBytes()
create a new byte array? In this case I extend my question to how to efficiently stream singleint
values ... -
MartinStettner over 13 yearsThanks, but I since need to control exactly which bytes are written, I'll go with
BinaryWriter
. -
Matt over 9 yearsIn a very unscientific test the buffer seems to handle looping over the array and calling Write(int) on each value efficiently. Thanks.
-
Nyerguds about 5 yearsDo be careful; stream wrappers like
BinaryWriter
tend to close the stream when they're done with it... not handy if you want to pass the stream with its written contents on to something else to handle stuff like writing it. -
Jon Skeet about 5 years@Nyerguds:
BinaryWriter
provides an option of leaving the stream open for precisely this reason. I haven't included details of that in the answer as the question didn't indicate that it was necessary. -
Nyerguds about 5 yearsI know, I just thought it was worth at least adding as comment because I ran into that issue again today... on an old 3.5 project, too, where that option isn't available. Ah well, dispose-blocking wrapper class it is.