Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetHashCode(key) & int.MaxValue

Tags:

c#

.net

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?

like image 751
MJ Richardson Avatar asked Jan 27 '12 01:01

MJ Richardson


People also ask

What is GetHashCode used for?

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.

Should I override GetHashCode?

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.

How does GetHashCode work C#?

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.

How do I find the Hashcode of a key?

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);


2 Answers

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.

like image 157
Ondrej Tucny Avatar answered Sep 23 '22 18:09

Ondrej Tucny


It will not affect positive numbers

  • [0, int.MaxValue] --> remains unchanged
  • [int.MinValue, -1] --> will alter the sign bit
like image 39
doblak Avatar answered Sep 21 '22 18:09

doblak