rwallace
rwallace

Reputation: 33455

How to add extra information to a hash code?

Given an array of bytes, there are several well-known good algorithms for calculating a hash code, such as FNV or MD5. (Not talking about cryptography here, just general purpose hash codes.)

Suppose what you have is an array of bytes plus one extra piece of information, a small integer (which is not located next to the array in memory), and you want a hash code based on the whole lot. What's the best way to do this? For example, one could take the hash code of the array and add it to the small integer, or exclusive-or them. But is there a better way?

Upvotes: 0

Views: 57

Answers (1)

olegarch
olegarch

Reputation: 3891

I think, more easiest and efficient way - just init "hash" accumulator with your small value, and thereafter compute hash by ordinary way. Following example illustrates my approach, where we compute hash from int and C-style string:

uint32_t hash(const char *str, uint32_t x) {
  char c;
  while((c = *str++) != 0)
      x = ((x << 5) | (x >> (32 - 5))) + c;
  return x ^ (x >> 16);
}

Upvotes: 2

Related Questions