Application of the KISS principle:
- SHA is just a string
- JDK hash code for
String
"random enough" Integer
can display in any database
This single line of code does this:
public static String shortHash(String sha) { return Integer.toString(sha.hashCode() & 0x7FFFFFFF, 36).substring(0, 3); }
Note. & 0x7FFFFFFF
is the zero bit of the sign (hash codes can be negative numbers that would otherwise be displayed using the minus sign).
Edit - Guarantee hash length
My initial decision was naive - it did not address the case where the int
hash is less than 100
(base 36) - this means that it prints less than 3 characters. This code fixes this while retaining the value of "random". It also avoids calling substring()
, so performance should be better.
static int min = Integer.parseInt("100", 36); static int range = Integer.parseInt("zzz", 36) - min; public static String shortHash(String sha) { return Integer.toString(min + (sha.hashCode() & 0x7FFFFFFF) % range, 36); }
This code ensures that the final hash has 3 characters, forcing it to be between 100
and zzz
- the lowest and highest tag <-> w980> in base 36, while still making it "random."
source share