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 GetHashCode method provides this hash code for algorithms that need quick checks of object equality. For information about how hash codes are used in hash tables and for some additional hash code algorithms, see the Hash Function entry in Wikipedia. Two objects that are equal return hash codes that are equal.
If you're implementing a reference type, you should consider overriding the Equals method if your type looks like a base type, such as Point, String, BigNumber, and so on. Override the GetHashCode method to allow a type to work correctly in a hash table.
GetHashCode() Method with Examples. This method is used to return the hash code for this instance. A hash code is a numeric value which is used to insert and identify an object in a hash-based collection.
GetHash(Object) method is used to get the hashcode of the specified key of a Hashtable object. This method is inherited from the Object Class. Syntax: protected virtual int GetHash(Object Key);
The value of int.MaxValue
is 0x7FFFFFFF
— 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 num
variable in you code sample.
It will not affect positive numbers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With