Absolute value java
-
21-12-2019 - |
Question
I am trying to create a directory with the name of the absolute value of the hexadecimal version of a hashed url, using the built-in hash() method of the String class. Now it is possible for hash() to produce a negative result, and a directory name starting with a minus sign is somewhat hard to handle which is why I need the absolute value of this. However, I cannot figure out how to get the absolute value of the hexadecimal version of the hashed url string.
Solution
The hex value never has a negative sign! It is just the hexadecimal representation of the two's compliment bit pattern of the value.
System.out.println(Integer.toHexString(-1)); // ffffffff
System.out.println(Integer.toHexString(Integer.MIN_VALUE)); // 80000000
Just like your mother always told you: "You're perfect just the way you are":
String dirname = Integer.toHexString(dirname.hashCode()); // never has minus sign
OTHER TIPS
Coerce it to a long, mask out the top 32 bits, then convert that to a string.
long longHash = intHash;
long nonNegativeLongHash = longHash & ((1L << 32) - 1);
String unsignedHex = Long.toHexString(nonNegativeLongHash);