将float转换为其二进制表示形式(使用MemoryStream?) [英] Convert float to its binary representation (using MemoryStream?)
问题描述
我想将给定的float
转换为其二进制表示形式.我试图将浮点值写入MemoryStream
,逐字节读取此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.
- 无法读取关闭的视频流"(但我只关闭了作家)
- 出于测试目的,我只写了一个整数(我认为是四个字节),当不刷新
StreamWriter
时,MemoryStream
的长度为0,而当我刷新时,其长度为1. li>
- "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.
我敢肯定有一种更好的方法可以将float
转换为二进制,但是我还想了解一些有关MemoryStream
类的信息.
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.
推荐答案
您可以使用 BinaryWriter.Write(float)
.目前尚不清楚您之前使用MemoryStream
做了什么,但是您不想想要使用StreamWriter
-这是用于文本的.
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.
这篇关于将float转换为其二进制表示形式(使用MemoryStream?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!