在Java VS C#intBitsToFloat方法? [英] intBitsToFloat method in Java VS C#?

查看:585
本文介绍了在Java VS C#intBitsToFloat方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

转换位在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆