EchtFettigerKeks
EchtFettigerKeks

Reputation: 1893

Get a Short from a UUID

My objects have a field of type "id":UUID. In my program, however, I also need a second ID for each object, which is displayed with shorts. I would prefer to derive / calculate this from the actual ID

Since a short only consists of two bytes, it is clear that I cannot just type-cast, but there may be a possibility to calculate a more or less unique short variable from the UUID-ID.

Does somebody has any idea?

Upvotes: 1

Views: 2370

Answers (1)

true_gler
true_gler

Reputation: 573

There are some options and things to consider.

An UUID consists of 128 bits. When you want represent it a smaller version (short = 16-bit) there is always a higher risk of collision!

There are two ways that I can think of to get a shorter "representation" or connection to your UUID:

  1. Direct Mapping to a number (I suggest using this)

Map the UUID to a short number (ranges from -32,768 to 32,767). Keep in mind you are limited in the amount using short. Just increment the number and map UUID and short ID.

Example:

123e4567-e89b-12d3-a456-426614174000 -> 1
e7511ef3-849e-4cee-b194-8f238ca88ce2 -> 2

If you really want to derive the second ID consider hashing:

  1. Hashing

Hashfunctions map data to fixed-size values. So you can use a Hashfunction to reduce the size. For example, a Pearson Hash is a 8 bit hash function or Fletcher-16 is a 16 bit hash function.

Additionally, UUIDs have a static part maybe you can ignore it and find a mapping function yourself.

Upvotes: 3

Related Questions