Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 597
Cubi73 Avatar asked Jan 20 '14 21:01

Cubi73


2 Answers

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.

like image 131
Jon Skeet Avatar answered Sep 23 '22 20:09

Jon Skeet


Using BitConverter, not MemoryStream:

        // -7 produces "1 10000001 11000000000000000000000"
        static string FloatToBinary(float f)
        {
            StringBuilder sb = new StringBuilder();
            Byte[] ba = BitConverter.GetBytes(f);
            foreach (Byte b in ba)
                for (int i = 0; i < 8; i++)
                {
                    sb.Insert(0,((b>>i) & 1) == 1 ? "1" : "0");
                }
            string s = sb.ToString();
            string r = s.Substring(0, 1) + " " + s.Substring(1, 8) + " " + s.Substring(9); //sign exponent mantissa
            return r;
        }
like image 36
xyq.384.b Avatar answered Sep 23 '22 20:09

xyq.384.b