A long value is passed to my component, which I later use as a key as a cache. The key itself is a string representation of a long value, as if it were an unsigned 64-bit value. That is, when my component is passed -2944827264075010823L, I need to convert it to the string key "15501916809634540793".
I have a solution, but it seems like brute force, and it makes me a little nauseous. Essentially, I convert the long to hexadecimal string representation (so -2944827264075010823L becomes "d721df34a7ec6cf9") and converts the hexadecimal string to BigInteger:
String longValueAsHexString = convertLongToHexString(longValue);
BigInteger bi = new BigInteger(longValueAsHexString, 16);
String longValueString = bi.toString();
Then I use longValueString as the key in the cache.
I cannot use Long.toString (longValue, 16) because it returns the sixth line for an absolute value with the prefix "-".
So my convertLongToHexString looks like this:
long mask = 0x00000000ffffffffL;
long bottomHalf = number & mask;
long upperHalf = (number >> 32) & mask;
String bottomHalfString = Long.toString(bottomHalf, 16);
if (bottomHalfString.length() != 8) {
String zeroes = "0000000000000000";
bottomHalfString = zeroes.substring(16-bottomHalfString.length()) + bottomHalfString;
}
return Long.toString(upperHalf,16)+bottomHalfString;
There should be a more elegant way to do this. Any suggestions?
Fred xavier
source
share