C# Why can equal decimals produce unequal hash values?

前端 未结 6 1561
后悔当初
后悔当初 2020-12-08 06:43

We ran into a magic decimal number that broke our hashtable. I boiled it down to the following minimal case:

decimal d0 = 295.50000000000000000000000000m;
de         


        
6条回答
  •  自闭症患者
    2020-12-08 07:25

    Another bug (?) that results in different bytes representation for the same decimal on different compilers: Try to compile following code on VS 2005 and then VS 2010. Or look at my article on Code Project.

    class Program
    {
        static void Main(string[] args)
        {
            decimal one = 1m;
    
            PrintBytes(one);
            PrintBytes(one + 0.0m); // compare this on different compilers!
            PrintBytes(1m + 0.0m);
    
            Console.ReadKey();
        }
    
        public static void PrintBytes(decimal d)
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
    
            binaryWriter.Write(d);
    
            byte[] decimalBytes = memoryStream.ToArray();
    
            Console.WriteLine(BitConverter.ToString(decimalBytes) + " (" + d + ")");
        }
    }
    

    Some people use following normalization code d=d+0.0000m which is not working properly on VS 2010. Your normalization code (d=d/1.000000000000000000000000000000000m) looks good - I use the same one to get the same byte array for the same decimals.

提交回复
热议问题