0

I'm using some code to generate a 16 bytes length String and I noticed a strange behaviour while using my code which is:

public static String generateMyUniqueString() {
    return new BigInteger(64,oRandom).toString(16);
}

This is giving me a nice 16 characters length string 99% of the time.
But yes, sometimes, the generated string is 15 characters length and, for now, I did not find why.

Gregordy
  • 517
  • 8
  • 16

2 Answers2

1

Your code reads:

Generate a random secure 64-bit integer and convert it to a hexadecimal string.

When it's converted to a string, leading zeroes are omitted. If you are really lucky you could also get a result with 14 or less digits.

If you want to always have a 16-digit value, you need to add leading zeros manually.

see: https://stackoverflow.com/a/6185386/3264295 for an example how to pad a string

Community
  • 1
  • 1
mukunda
  • 2,666
  • 11
  • 18
1

I suggest you try

public static String generateMyUniqueString() {
    return String.format("%016x", new BigInteger(64, oRandom));
}

This will always be 16 digits long as it zero pads the start.

BTW: if you generate 4 billion of these ids there is a 50/50 changes two will be the same.

Have you considered using UUID (128 bit), or a durable counters instead?

Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075