如何解析有符号零? [英] How to parse signed zero?
问题描述
是否可以解析带符号的零? 我尝试了几种方法,但没有人给出正确的结果:
Is it possible to parse signed zero? I tried several approaches but no one gives the proper result:
float test1 = Convert.ToSingle("-0.0");
float test2 = float.Parse("-0.0");
float test3;
float.TryParse("-0.0", out test3);
如果我使用直接初始化的值就可以了:
If I use the value directly initialized it is just fine:
float test4 = -0.0f;
所以问题似乎出在c#的解析过程中.我希望有人能告诉您是否有某些选择或解决方法.
So the problem seems to be in the parsing procedures of c#. I hope somebody could tell if there is some option or workaround for that.
只能通过转换为二进制来看到区别:
The difference could only be seen by converting to binary:
var bin= BitConverter.GetBytes(test4);
推荐答案
我认为没有办法强制float.Parse
(或Convert.ToSingle
)尊重负零.它就是这样工作的(在这种情况下忽略符号).因此,您必须检查一下自己,例如:
I think there is no way to force float.Parse
(or Convert.ToSingle
) to respect negative zero. It just works like this (ignores sign in this case). So you have to check that yourself, for example:
string target = "-0.0";
float result = float.Parse(target, CultureInfo.InvariantCulture);
if (result == 0f && target.TrimStart().StartsWith("-"))
result = -0f;
如果我们查看源代码对于coreclr,我们将看到(跳过所有不相关的部分):
If we look at source code for coreclr, we'll see (skipping all irrelevant parts):
private static bool NumberBufferToDouble(ref NumberBuffer number, ref double value)
{
double d = NumberToDouble(ref number);
uint e = DoubleHelper.Exponent(d);
ulong m = DoubleHelper.Mantissa(d);
if (e == 0x7FF)
{
return false;
}
if (e == 0 && m == 0)
{
d = 0; // < relevant part
}
value = d;
return true;
}
如您所见,如果尾数和指数均为零,则将值显式分配给0
.因此,您无法更改它.
As you see, if mantissa and exponent are both zero - value is explicitly assigned to 0
. So there is no way you can change that.
.NET的完整实现具有NumberBufferToDouble
作为InternalCall
(在纯C \ C ++中实现),但是我认为它执行的操作类似.
Full .NET implementation has NumberBufferToDouble
as InternalCall
(implemented in pure C\C++), but I assume it does something similar.
这篇关于如何解析有符号零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!