Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reduce length of UUID generated using randomUUID( )

Tags:

java

uuid

I have a short utility in which I am generating a UUID using randomUUID().

String uuid = UUID.randomUUID().toString(); 

However, the uuid generated is too long which is 36 in length.

Is there anyway I can reduce the length of the UUID from 36 to near to 16 or 16 ?

like image 326
AppleBud Avatar asked Jan 08 '14 11:01

AppleBud


People also ask

Is there a shorter version of UUID?

NanoID is Only 108 bytes in Size Unlike UUID, NanoID is 4.5 times smaller in size and does not have any dependencies.

Does UUID have fixed length?

UUID Format UUIDs have 32 digits plus 4 hyphens for a total of 36 characters. UUIDs are fixed length. UUIDs are 128-bits in binary. (32 hex digits x 4 bits per hex digit = 128-bits).

What is the length of UUID in Java?

A UUID is made up of hex digits (4 chars each) along with 4 “-” symbols, which make its length equal to 36 characters. The Nil UUID is a special form of UUID in which all bits are set to zero.

What is the length of a UUID?

What is a UUID. Universally Unique Identifiers, or UUIDS, are 128 bit numbers, composed of 16 octets and represented as 32 base-16 characters, that can be used to identify information across a computer system. This specification was originally created by Microsoft and standardized by both the IETF and ITU.


1 Answers

If you don't need it to be unique, you can use any length you like.

For example, you can do this.

Random rand = new Random(); char[] chars = new char[16]; for(int i=0;i<chars.length;i++) {     chars[i] = (char) rand.nextInt(65536);     if (!Character.isValidCodePoint(chars[i]))         i--; } String s = new String(chars); 

This will give you almost the same degree of randomness but will use every possible character between \u0000 and \ufffd

If you need printable ASCII characters you can make it as short as you like but the likelihood of uniqueness drops significantly. What can do is use base 36 instead of base 16

UUID uuid = UUID.randomUUID(); String s = Long.toString(uuid.getMostSignificantBits(), 36) + '-' + Long.toString(uuid.getLeastSignificantBits(), 36); 

This will 26 characters on average, at most 27 character.

You can use base64 encoding and reduce it to 22 characters.

If you use base94 you can get it does to 20 characters.

If you use the whole range of valid chars fro \u0000 to \ufffd you can reduce it to just 9 characters or 17 bytes.

If you don't care about Strings you can use 16, 8-bit bytes.

like image 130
Peter Lawrey Avatar answered Sep 28 '22 06:09

Peter Lawrey