Without unsafe context and mixing NaN , + Inf , -Inf :
var isFinite = ((BitConverter.DoubleToInt64Bits(d) >> 52) & 0x7ff) != 0x7ff;
Explanation:
The double value is 64 bits, which is stored as:
- 1 bit for sign
- 11 bit for exhibitor
- 52 bits for mantissa
Bit No: 63 62 ~~~~~~~ 52 51 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~ 0
Bit: 0 00000000000 0000000000000000000000000000000000000000000000000000
sign exponent mantissa
If sign = 0 && exponent == 11111111111 && mantissa == 0 => + Infinity
If sign = 1 && exponent == 11111111111 && mantissa == 0 => -Infinity
If exponent == 11111111111 && mantissa! = 0 => NaN
If exponent! = 11111111111 => Finite
In other terms:
If exponent == 11111111111 => Not finite
If exponent! = 11111111111 => Finite
Step 1: Convert double as Int64 bits (DoubleToInt64Bits)
Step 2: Shift right 52 bits to remove mantissa (>> 52)
Step 3: Mask exponent bits to remove sign (& 0x7ff)
Step 4: Check if all remaining bits are set to 1
Note: 0b11111111111 = 0x7ff = 2047
Finally, this can be simplified to :
var isFinite = (BitConverter.DoubleToInt64Bits(d) & 0x7ff0000000000000) != 0x7ff0000000000000;
In extension method and unsafe :
internal static class ExtensionMethods { public static unsafe bool IsFinite(this double d) => (*(long*)&d & 0x7ff0000000000000) != 0x7ff0000000000000; }
Test
Console.WriteLine("NegativeInfinity is " + (double.NegativeInfinity.IsFinite() ? "finite" : "not finite")); Console.WriteLine("PositiveInfinity is " + (double.PositiveInfinity.IsFinite() ? "finite" : "not finite")); Console.WriteLine("NaN is " + (double.NaN.IsFinite() ? "finite" : "not finite")); Console.WriteLine("Epsilon is " + (double.Epsilon.IsFinite() ? "finite" : "not finite")); Console.WriteLine("MinValue is " + (double.MinValue.IsFinite() ? "finite" : "not finite")); Console.WriteLine("MaxValue is " + (double.MaxValue.IsFinite() ? "finite" : "not finite"));
Result
NegativeInfinity is not finite
PositiveInfinity is not finite
NaN is not finite
Epsilon is finite
MinValue is finite
MaxValue is finite
source share