Search code examples
c#binarymemorystreamfloating-point-conversion

Convert float to its binary representation (using MemoryStream?)


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 the StreamWriter, and 1, when I did.

I'm sure there is a better way to convert floats to binary, but I also wanted to learn a little bit about the MemoryStream class.


Solution

  • You can use BitConverter.GetBytes(float) or use a BinaryWriter wrapping a MemoryStream and use BinaryWriter.Write(float). It's not clear exactly what you did with a MemoryStream before, but you don't want to use StreamWriter - that's for text.