GetHashCode (key) & int.MaxValue

When looking at the implementation of the generic Dictionary<TKey, TValue> in mscorlib.dll, I noticed that the following was used many times to get the hash key:

 int num = this.comparer.GetHashCode(key) & int.MaxValue; 

GetHashCode () returns an int. Am I mistaken in thinking that bitwise AND between int.MaxValue and any integer x will always return x?

Can someone explain why the operator is used in this way above?

+7
source share
2 answers

The value of int.MaxValue is 0x7FFFFFFF - the most significant bit is zero. Therefore, when you execute bitwise and with another int, you actually nullify the β€œsign” bit. Please note that due to the used coding of the two additions, -1 will not become 1, but will be 2 147 483 647.

Apparently, for some reason, only positive integers in the code sample are allowed in the num variable.

+10
source

This will not affect positive numbers.

  • [0, int.MaxValue] β†’ remains unchanged
  • [int.MinValue, -1] β†’ will change the sign bit
+1
source

All Articles