intBitsToFloat method in Java VS C#?

China☆狼群 提交于 2019-12-04 06:32:18

问题


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


回答1:


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);



回答2:


i want to add on top of what jon skeet said, that also, for big float, if you don't want the "E+" output you should do:

intbits.ToString("N0");



回答3:


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. Then BitConverter.ToSingle converts your array into a float(single).



来源:https://stackoverflow.com/questions/18079000/intbitstofloat-method-in-java-vs-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!