Hash function for floats

前端 未结 6 1588
野趣味
野趣味 2020-12-03 07:38

I\'m currently implementing a hash table in C++ and I\'m trying to make a hash function for floats...

I was going to treat floats as integers by padding the decimal

6条回答
  •  死守一世寂寞
    2020-12-03 07:59

    unsigned hash(float x)
    {
        union
        {
            float f;
            unsigned u;
        };
        f = x;
        return u;
    }
    

    Technically undefined behavior, but most compilers support this. Alternative solution:

    unsigned hash(float x)
    {
        return (unsigned&)x;
    }
    

    Both solutions depend on the endianness of your machine, so for example on x86 and SPARC, they will produce different results. If that doesn't bother you, just use one of these solutions.

提交回复
热议问题