While browsing the implementation of the generic Dictionary<TKey, TValue> class in mscorlib.dll, I noticed the following used many times to get a hash-key:
int num = this.comparer.GetHashCode(key) & int.MaxValue;
GetHashCode() returns an int. Am I mistaken in thinking that a bitwise AND between int.MaxValue and any integer x, will always return x?
Can someone explain why the & operator is used in the manner above?
The value of
int.MaxValueis0x7FFFFFFF— the most significant bit is zero. Hence when you perform a bitwise and with another int, you effectively zero-out the ‘sign’ bit. Note that because of the two’s complement encoding used, -1 won’t become 1 but rather 2,147,483,647.Apparently, for some reason only positive integers are allowed in the
numvariable in you code sample.