Created
March 7, 2016 07:27
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output;
Hash[dummyHash] for longValueOne : 8
Hash[dummyHash] for longValueTwo : 8
Hash[folding] for longValueOne : 1097859072
Hash[folding] for longValueTwo : 1075838976