将float转换为二进制表示(使用MemoryStream?)

Cub*_*i73 6 c# binary memorystream floating-point-conversion

我想将一个给定float转换为二进制表示.我试图将浮点值写入a MemoryStream,MemoryStream逐字节读取该字节并将字节转换为其二进制表示.但每次尝试都失败了.

  • "无法读取封闭的流"(但我只关闭了作者)
  • 出于测试目的,我简单地写了一个整数(我认为大小为4个字节)MemoryStream,当我没有刷新时为0 的长度,而当我做的时StreamWriter,为1.

我确信有一种更好的方法可以将floats 转换为二进制,但我也想了解一下这个MemoryStream类.

Jon*_*eet 12

您可以使用BitConverter.GetBytes(float)或使用BinaryWriter包装MemoryStream和使用BinaryWriter.Write(float).目前尚不清楚你所做的事有MemoryStream过,但你希望使用StreamWriter-这是文本.

  • 在[本页]上找到了一些东西(http://stackoverflow.com/questions/24420086/specify-a-specific-double-precision-literal-in-c-sharp).使用不安全指针转换:`ulong db =*(ulong*)&d;`或`uint fb =*(uint*)&f;`.这可能是最有效的方式. (2认同)

小智 5

使用 BitConverter,而不是 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;
        }
Run Code Online (Sandbox Code Playgroud)