I have scenario in the application where I need to generate an ID which should be Random 64 bit value in hex representation,
What I have done so far,
Random randomLong = new Random();
long m = randomLong.nextLong();
String uid = Long.toHexString(m);
The o/p could be like 43c45c243f90326a or 82cf8e3863102f3a etc. But not every time it gives 16 character, but 15 characters instead I don't get why :(
What is the most efficient way to get Random 64 bit value in hex representation which contains 16 characters
Use String.format()
long value=123L;
String uid = String.format("%016x", value);
// 000000000000007b
A word of explanation:
Each hex digit represents 4-bits. A 64-bit long can be represented by 16 (64/4) hexadecimal characters. To include the leading zeros, you want 16 hex digits. So your format specifier is %016x
. Basically, %x
for hex modified by inserting 016
to left-pad with zeros to achieve a minimum width of 16 characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With