[英]Byte array to float
I am trying to cast a float into a byte array of length 4, and then back again. 我试图将浮点数转换为长度为4的字节数组,然后再返回。 But I it doesn's seems to work.
但我似乎没有工作。
Here's what I've done: 这就是我所做的:
byte[] b = BitConverter.GetBytes(90);
float fb = BitConverter.ToSingle(b, 0);
I expected fb = 90, but it's 1.26E-43. 我预计fb = 90,但它是1.26E-43。
I know that my converter is little endian, so I've also tried to reverse the array, like this: 我知道我的转换器是小端,所以我也尝试反转数组,如下所示:
byte[] b = BitConverter.GetBytes(90);
Array.Reverse(b);
float fb = BitConverter.ToSingle(b, 0);
Then I got the answer fb = 9.0E+15. 然后我得到了答案fb = 9.0E + 15。
Any ideas? 有任何想法吗? Thanks in advance!
提前致谢!
BitConverter.GetBytes(90);
will give you the bytes for the integer value of 90
. 将为您提供整数值为
90
的字节。 Since you want the bytes for the float
value, you need to specify that: 由于您需要
float
值的字节,因此需要指定:
BitConverter.GetBytes((float)90.0);
or 要么
BitConverter.GetBytes(90.0f);
You need to change the input on the GetBytes, it's an integer now. 你需要改变GetBytes的输入,现在它是一个整数。
It's now getting the bytes on how the integer is stored and interpretate as how a float would be stored in memory. 它现在得到整数存储方式的字节,并解释为浮点数将如何存储在内存中。
Change it to a float. 将其更改为浮动。
Try: 尝试:
byte[] b = BitConverter.GetBytes(90f); // <-- add an f for floats.
Array.Reverse(b);
float fb = BitConverter.ToSingle(b, 0);
90
is a literal that is interpreted by the compiler as Int32
, not as Single
. 90
是由编译器解释为Int32
而不是Single
的文字。 So you call the wrong overload of GetBytes()
. 所以你调用
GetBytes()
的错误重载。
Use: byte[] b = BitConverter.GetBytes(90f);
使用:
byte[] b = BitConverter.GetBytes(90f);
to tell the compiler you want to call GetBytes(float)
. 告诉编译器你要调用
GetBytes(float)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.