I'd like to convert a given float
into its binary representation. I tried to write the float value into a MemoryStream
, read this MemoryStream
byte by byte and convert the bytes into their binary representation. But every attempt failed.
- "Can't read closed stream" (but I only closed the writer)
- For test purposes I simply wrote an integer (I think four bytes in size) and the length of the
MemoryStream
was 0, when I didn't flush theStreamWriter
, and 1, when I did.
I'm sure there is a better way to convert float
s to binary, but I also wanted to learn a little bit about the MemoryStream
class.
Using BitConverter, not MemoryStream:
You might have run into a pitfall when using StreamWriter, as the following code shows:
If you expect only 4 bytes to be in the stream and read those 4 bytes, everything looks fine at first sight. But actually the length is 7 and you have read only the first 4 bytes of the text representation of the float.
Comparing that to the output of the BitConverter reveals that using StreamWriter is not the correct thing here.
You can use
BitConverter.GetBytes(float)
or use aBinaryWriter
wrapping aMemoryStream
and useBinaryWriter.Write(float)
. It's not clear exactly what you did with aMemoryStream
before, but you don't want to useStreamWriter
- that's for text.To answer your first question: In .Net, when you close/dispose a reader/writer, the underlying stream is also closed/disposed.
Dotnetfiddle
Couldn't resist to use a "small" LINQ Query. Works with double too.