Skip to content

Instantly share code, notes, and snippets.

@bzdgn
Created March 7, 2016 07:27
Show Gist options
  • Save bzdgn/375597c00b261110bb4e to your computer and use it in GitHub Desktop.
Save bzdgn/375597c00b261110bb4e to your computer and use it in GitHub Desktop.
Generating 32-bit Integer Hash Code for 64-bit long values with folding
package com.levo.hashing;
public class HashForLong {
public static void main(String[] args) {
long longValueOne = new Long(Integer.MAX_VALUE) + new Long(Integer.MAX_VALUE) + new Long(10);
long longValueTwo = 8;
// Following hashing function is not working, different numbers return same result
System.out.println("Hash[dummyHash] for longValueOne : " + dummyHash(longValueOne));
System.out.println("Hash[dummyHash] for longValueTwo : " + dummyHash(longValueTwo));
// hashing function with folding, differnt numbers different hash codes
System.out.println("Hash[folding] for longValueOne : " + folding(longValueOne));
System.out.println("Hash[folding] for longValueTwo : " + folding(longValueTwo));
}
private static int dummyHash(long value) {
return (int)value;
}
private static int folding(long value) {
long bits = Double.doubleToLongBits(value);
return (int)( bits ^ (bits>>32));
}
}
@bzdgn
Copy link
Author

bzdgn commented Mar 7, 2016

Output;

Hash[dummyHash] for longValueOne : 8
Hash[dummyHash] for longValueTwo : 8
Hash[folding] for longValueOne : 1097859072
Hash[folding] for longValueTwo : 1075838976

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment