[英]intBitsToFloat method in Java VS C#?
I'm getting the wrong number when converting bits to float in C#. 将位转换为C#时出现错误编号。
Let's use this bit number= 1065324597
让我们使用此位数
number= 1065324597
In Java , if I want to convert from bits to float I would use intBitsToFloat
method 在Java中 ,如果要从位转换为浮点数,可以使用
intBitsToFloat
方法
int intbits= 1065324597;
System.out.println(Float.intBitsToFloat(intbits));
Output: 0.9982942
which the correct output the I want to get in C# 输出:
0.9982942
我想在C#中获得的正确输出
However, in C# I used 但是,在C#中,我使用了
int intbits= 1065324597;
Console.WriteLine((float)intbits);
Output: 1.065325E+09
Wrong!! 输出:
1.065325E+09
错误!
My question is how would you convert inbitsToFloat in C#? 我的问题是如何在C#中转换inbitsToFloat?
My attempt: I looked to the documentation here http://msdn.microsoft.com/en-us/library/aa987800(v=vs.80).aspx but I still have the same trouble 我的尝试:我在这里查看了文档http://msdn.microsoft.com/zh-cn/library/aa987800(v=vs.80).aspx,但是仍然遇到同样的麻烦
Just casting is an entirely different operation. 只是投射是完全不同的操作。 You need
BitConverter.ToSingle(byte[], int)
having converted the int
to a byte array - and possibly reversed the order, based on the endianness you want. 您需要
BitConverter.ToSingle(byte[], int)
将int
转换为字节数组-并可能根据所需的字节序反转顺序。 (EDIT: Probably no need for this, as the same endianness is used for both conversions; any unwanted endianness will just fix itself.) There's BitConverter.DoubleToInt64Bits
for double
, but no direct float
equivalent. (编辑:可能不需要这样做,因为两次转换都使用相同的字节序;任何不想要的字节序都将自行修复。)对于
double
,有BitConverter.DoubleToInt64Bits
,但是没有等效的直接float
。
Sample code: 样例代码:
int x = 1065324597;
byte[] bytes = BitConverter.GetBytes(x);
float f = BitConverter.ToSingle(bytes, 0);
Console.WriteLine(f);
我想在乔恩·斯凯特说的话之上加上,对于大浮点数,如果您不希望“ E +”输出,也应该这样做:
intbits.ToString("N0");
Just try this... 试试这个...
var myBytes = BitConverter.GetBytes(1065324597);
var mySingle = BitConverter.ToSingle(myBytes,0);
The BitConverter.GetBytes converts your integer into a four byte array. BitConverter.GetBytes将整数转换为四个字节的数组。 Then BitConverter.ToSingle converts your array into a float(single).
然后,BitConverter.ToSingle将您的数组转换为float(单)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.