Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 652
tyro Avatar asked Sep 11 '25 02:09

tyro


1 Answers

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.

like image 158
phatfingers Avatar answered Sep 13 '25 16:09

phatfingers