[英]Byte Array to Float Conversion C#
I have tried the below C# code to convert from hex literal to floating point and get the correct result. 我已经尝试过下面的C#代码从十六进制文字转换为浮点数并获得正确的结果。 I wish to input a byte array instead and have that converted to floating point but can't seem to get it right result.
我希望输入一个字节数组,并将其转换为浮点数,但似乎无法获得正确的结果。
0x4229ec00
is the current format. 0x4229ec00
是当前格式。 I need it in byte array
format something like... 我需要
byte array
格式的东西像...
new byte[]{ 0x01, 0x04, 0x01, 0x60, 0x00, 0x02, 0x70, 0x29}; //current output 42.48
The code looks like: 代码如下:
byte[] bytes = BitConverter.GetBytes(0x4229ec00);
float myFloat = floatConversion(bytes);
public float floatConversion(byte[] bytes)
{
float myFloat = BitConverter.ToSingle(bytes, 0);
return myFloat;
}
Any help would be greatly appreciated. 任何帮助将不胜感激。 Thank you!
谢谢!
You can amend your float conversion function as below 您可以如下修改浮点转换功能
public float floatConversion(byte[] bytes)
{
if (BitConverter.IsLittleEndian)
{
Array.Reverse(bytes); // Convert big endian to little endian
}
float myFloat = BitConverter.ToSingle(bytes, 0);
return myFloat;
}
float ( Single
) is a 4 Byte value; float (
Single
)是一个4字节的值;
Your test value 0x4229ec00 contains 4 bytes, they are: 0x42, 0x29, 0xEC, 0x00 您的测试值0x4229ec00包含4个字节,分别是: 0x42、0x29、0xEC ,0x00
x86 CPUs use reversed order of bytes ( Little Endian ), so the right byte array is x86 CPU使用相反的字节顺序 ( Little Endian ),因此右字节数组为
0x00, 0xEC, 0x29, 0x42
The Code 编码
// Original array
Byte[] data = new Byte[] {0x42, 0x29, 0xEC, 0x00};
// 42.48047
// If CPU uses Little Endian, we should reverse the data
float result = BitConverter.ToSingle(BitConverter.IsLittleEndian? data.Reverse().ToArray() : data, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.