Question

I'm working with hash tables and I came across this function. But what does hash / sizeof(void *) mean? and the comment given after it - get rid of known-0 bits?

// This matches when the hashtable key is a pointer.
      template<class HashKey> class hash_munger<HashKey*> {
       public:
        static size_t MungedHash(size_t hash) {
          // TODO(csilvers): consider rotating instead:
          //    static const int shift = (sizeof(void *) == 4) ? 2 : 3;
          //    return (hash << (sizeof(hash) * 8) - shift)) | (hash >> shift);
          // This matters if we ever change sparse/dense_hash_* to compare
          // hashes before comparing actual values.  It's speedy on x86.
          return hash / sizeof(void*);   // get rid of known-0 bits
        }
      };
Was it helpful?

Solution

On most machines and ABIs, pointers are generally word-aligned. So dividing by the sizeof pointers is essentially ignoring the least bits (e.g. 3 lowest bits of bytes addresses are 0 on most 64 bits processors since a 64 bits word has 8 bytes, each of 8 bits).

OTHER TIPS

It looks like it is a function to hash a pointer. Pointers point to objects, which are often aligned. If the object here being pointed to is allocated with "new" it is most likely to be aligned to the word boundary.

Therefore, it may possibly always be divisible by 8 (or 4 if that is the word size) (when converted to a number) and the function is dividing your number by 8 to give you what is really significant about your pointer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top