7

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

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

4 Comments

In a very unscientific test the buffer seems to handle looping over the array and calling Write(int) on each value efficiently. Thanks.
Do 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.
@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.
I 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.
3

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.