How can I specify a specific double
precision literal or value in c#?
For example, I would like to use the constant of the largest double
value less than one in a program. The largest double
less than one is 1.11111111 11111111 11111111 11111111 11111111 11111111 1111 x 2^(-1)
in binary. Expressing this as a big-endian double in hex would be 0x3fe f ffff ffff ffff
I can generate it with the following code:
var largestDoubleLessThanOneBytes = new byte[] {0x3f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
if (BitConverter.IsLittleEndian) largestDoubleLessThanOneBytes = largestDoubleLessThanOneBytes.Reverse().ToArray();
double largestDoubleLessThanOne = BitConverter.ToDouble(largestDoubleLessThanOneBytes, 0);
BitConverter
can't be used in the declaration of a const
, so this can't be used in place of a literal value.
Using this tool, I can come up with the literal 9.99999999999999888977697537484E-1
, which ends up being exactly the same double. BitConverter.ToString(BitConverter.GetBytes(9.99999999999999888977697537484E-1)) == "FF-FF-FF-FF-FF-FF-EF-3F"
.
Is there any other way to get specific double
values into c# code than to find a decimal literal whose closest double representation is the double you want?