How to create a string representing Java as if it were an unsigned 64 bit value

My component was passed a long value, which I later used as a key in the 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 handed over to - 2944827264075010823l, I need to convert it to the string key "1550191689634540793"

I have a solution, but it seems brute force, it makes me a little uneasy In essence, I convert long to hexadecimal string representation (so - 2944827264075010823l becomes "d721df34a7ec6cf9") and convert hexadecimal string to BigInteger:

String longValueAsHexString = convertLongToHexString(longValue);
BigInteger bi = new BigInteger(longValueAsHexString,16);
String longValueString = bi.toString();

Then I use longvaluestring as the cache key

I can't use long ToString (longvalue, 16), because it returns the hexadecimal string of absolute value, prefixed with "–"

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 must be a more elegant way to do this Any suggestions?

Solution

This is my implementation I refactor it with a function that takes a long time and returns a string

The above is all about how to create a string representing Java, just as it is an unsigned 64 bit value. I hope this article can help you solve the program development problem of how to create a string representing Java, just as it is an unsigned 64 bit value.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>