language: C# (mono-2.8)
date: 665 days 6 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Program
{
    static string EncodeDouble(double d)
    {
        long ieee = System.BitConverter.DoubleToInt64Bits(d);
        ulong widezero = 0;
        ulong lex = ((ieee < 0)? widezero: ((~widezero) >> 1)) ^ (ulong)~ieee;
        return lex.ToString("X16");
    }
 
    static double DecodeDouble(string s)
    {
        ulong lex = ulong.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
        ulong widezero = 0;
        long ieee = (long)(((0 <= (long)lex)? widezero: ((~widezero) >> 1)) ^ ~lex);
        return System.BitConverter.Int64BitsToDouble(ieee);
    }
 
    static void Test(double a, double b)
    {
        System.Console.WriteLine(a.ToString() + " <=> " + b.ToString() + (a.CompareTo(b) == EncodeDouble(a).CompareTo(EncodeDouble(b))? " : pass" : " : fail"));
    }
 
    static void Roundtrip(double a)
    {
        System.Console.WriteLine(a.ToString() + (a == DecodeDouble(EncodeDouble(a))? " roundtrips": " fails"));
    }
 
    static void Main()
    {
        Test(2, 2);
        Test(2, 3);
        Test(2, 20);
        Test(2, 0.5);
        Test(2, -2);
        Test(-2, -3);
        Test(-2, -20);
        Test(-2, -0.5);
 
        Roundtrip(2);
        Roundtrip(3);
        Roundtrip(20);
        Roundtrip(0.5);
        Roundtrip(-2);
        Roundtrip(-3);
        Roundtrip(-0.5);
    }
}