在Java VS C#intBitsToFloat方法? [英] intBitsToFloat method in Java VS C#?
问题描述
让我们用这个位 number = 1065324597
在 Java 中,如果我想从位转换为float,我将使用 intBitsToFloat
方法
int intbits = 1065324597;
System.out.println(Float.intBitsToFloat(intbits));
输出: 0.9982942
$ b
然而,在<我用
int intbits = 1065324597;
Console.WriteLine((float)intbits);
输出: 1.065325E + 09
我的问题是如何转换在C#中的inbitsToFloat? strong>我的企图:
我看这里的文档 http://msdn.microsoft.com/en-us/library/aa987800(v = vs.80).aspx
但我仍然有同样的问题只是铸造是完全不同的操作。您需要 BitConverter.ToSingle(byte [] ,int)
已经将 int
转换为一个字节数组,并且可能会颠倒顺序,这取决于您想要的字节顺序。 (编辑:也许不需要这样,因为相同的字节顺序用于两个转换;任何不需要的字节顺序将只是自我修正)有 BitConverter.DoubleToInt64Bits
为 double
,但是没有直接的 float
等值。 p>
int x = 1065324597;
byte [] bytes = BitConverter.GetBytes(x);
float f = BitConverter.ToSingle(bytes,0);
Console.WriteLine(f);
I'm getting the wrong number when converting bits to float in C#.
Let's use this bit number= 1065324597
In Java, if I want to convert from bits to float I would use intBitsToFloat
method
int intbits= 1065324597;
System.out.println(Float.intBitsToFloat(intbits));
Output: 0.9982942
which the correct output the I want to get in C#
However, in C# I used
int intbits= 1065324597;
Console.WriteLine((float)intbits);
Output: 1.065325E+09
Wrong!!
My question is how would you convert inbitsToFloat in C#?
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
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. (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.
Sample code:
int x = 1065324597;
byte[] bytes = BitConverter.GetBytes(x);
float f = BitConverter.ToSingle(bytes, 0);
Console.WriteLine(f);
这篇关于在Java VS C#intBitsToFloat方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!