Amruta Desai Amruta Desai -4 years ago 57
Java Question

64 bit Random number value in hex gives 16 characters sometimes 15 characters why?

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download