Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

GetHashcode - Int too small capacity?

Discussion in 'Scripting' started by gfrast, Apr 19, 2017.

  1. gfrast

    gfrast

    Joined:
    May 5, 2014
    Posts:
    30
    Right now I'm implementing a Vector3 struct only with INTs. i did some research to figure out how to write a proper hashcode for 3 Ints, and i stumbled upon this page (also referenced by many other pages talking about hashcodes):
    http://stackoverflow.com/questions/...m-for-an-overridden-system-object-gethashcode
    Code (CSharp):
    1.  
    2. public override int GetHashCode()
    3. {
    4.    unchecked // Overflow is fine, just wrap
    5.    {
    6.        int hash = 17;
    7.        // Suitable nullity checks etc, of course :)
    8.        hash = hash * 23 + field1.GetHashCode();
    9.        hash = hash * 23 + field2.GetHashCode();
    10.        hash = hash * 23 + field3.GetHashCode();
    11.        return hash;
    12.    }
    13. }
    14.  
    Now, i implemented the HashCode as follows:
    Code (CSharp):
    1.         public override int GetHashCode()
    2.         {
    3.             int hash = 17;
    4.  
    5.             hash = hash * 486187739 + x.GetHashCode();
    6.             hash = hash * 486187739 + y.GetHashCode();
    7.             hash = hash * 486187739 + z.GetHashCode();
    8.             return hash;
    9.         }
    My question is - the number returned is incredibly large, and can actually not be stored in the returned INT. How come, this is the suggested prime number then? Am i missing an important step in the implementation?

    Cheers and thanks upfront!
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I think it will just truncate/overflow silently, if the number cannot fit.
    Provided overflow checking is disabled or if enabled, the code is written inside a 'checked' statement.
     
    Last edited: Apr 19, 2017
    gfrast likes this.
  3. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Yes. You removed "unchecked". The "unchecked" keyword is what makes it ignore the overflow and return anyway. If you get rid of that, it's going to throw an OverflowException.
     
    gfrast likes this.
  4. gfrast

    gfrast

    Joined:
    May 5, 2014
    Posts:
    30
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    :) Awesome.