如何检查C#中给定的双数是否正常,即既不是零,次正规,无穷也不是NaN。
在C ++中,有一个方法std :: isnormal正是在检查这种情况。C#是否有等效功能?
const long ExponentMask = 0x7FF0000000000000;
static bool IsSubnormal(double v)
{
long bithack = BitConverter.DoubleToInt64Bits(v);
if (bithack == 0) return false;
return (bithack & ExponentMask ) == 0;
}
static bool IsNormal(double v)
{
long bithack = BitConverter.DoubleToInt64Bits(v);
bithack &= ExponentMask;
return (bithack != 0) && (bithack != ExponentMask);
}
现在已经过测试。测试套件:static void TestValue(double d) { Console.WriteLine("value is {0}, IsSubnormal returns {1}, IsNormal returns {2}", d, IsSubnormal(d), IsNormal(d)); } static void TestValueBits(ulong bits) { TestValue(BitConverter.Int64BitsToDouble((long)bits)); } public static void Main(string[] args) { TestValue(0.0); TestValue(1.0); TestValue(double.NaN); TestValue(double.PositiveInfinity); TestValue(double.NegativeInfinity); TestValue(double.Epsilon); TestValueBits(0xF000000000000000); TestValueBits(0x7000000000000000); TestValueBits(0xC000000000000000); TestValueBits(0x4000000000000000); TestValueBits(0xFFF0000000000005); TestValueBits(0x7FF0000000000005); TestValueBits(0x8010000000000000); TestValueBits(0x0010000000000000); TestValueBits(0x8001000000000000); TestValueBits(0x0001000000000000); }
public static bool IsNormal(double d);
如果值正常,则返回true
;否则,返回0。false
否则。适用于。NET Core 3.1、3.0、2.2、2.1
。NET Standard 2.1