IEEE754到浮点C#
问题描述:
下面的代码简单地将32位整数从要传递的对象转换为函数,该32位整数表示一个浮点数.我已经使用在线计算器检查过,我得到正确的符号,指数和曼陀罗,但是奇怪的是我得到的答案是错误的.
The below code is simple converting a 32bit-integer from the object being passed to the function, the 32-bit integer represents a floating number. I have checked with an online calculator that that i am getting the sign, exponent and mantessa the correct way but strangely i am getting the answer wrong.
任何人都可以检查我是否在数学上(或者可能在编程上)以某种方式做错了吗??
Can anyone please check if i am mathematically (or maybe programmatically) doing it wrong somehow!?
致谢
public double FromFloatSafe(object f)
{
uint fb = Convert.ToUInt32(f);
uint sign, exponent = 0, mantessa = 0;
uint bias = 127;
sign = (fb >> 31) & 1;
exponent = (fb >> 23) & 0xFF;
mantessa = (fb & 0x7FFFFF);
double fSign = Math.Pow((-1), sign);
double fMantessa = 1 + (1 / mantessa);
double fExponent = Math.Pow(2, (exponent -bias));
double ret = fSign * fMantessa * fExponent;
return ret;
}
答
类似的东西:
uint fb = Convert.ToUInt32(f);
return BitConverter.ToSingle(BitConverter.GetBytes((int) fb), 0);