Generate ID from UUID

This is a method to generate a long id in the positive space.

There are few issues to consider with this method
– UUID is 16 bytes / 128 bits
– Long is 8 bytes / 64 bits

This means that we will loose some information, if we don’t want to lose that we could use a BigInteger but In this case we are dealing with longs.

     * Gnereate unique ID from UUID in positive space
     * @return long value representing UUID
    private Long generateUniqueId()
        long val = -1;
            final UUID uid = UUID.randomUUID();
            final ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
            final BigInteger bi = new BigInteger(buffer.array());
            val = bi.longValue();
        } while (val < 0);
        return val;

This works simply by creating new BigInteger from parts of UUID object, and then getting the longValue. We also make sure that the ID is in positive space, if its not we simply repeat the process. During testing most cases completed in one iteration but it did encounter few runs that reached four iterations.

2 thoughts on “Generate ID from UUID

  1. BigInteger.longValue may return (this % 2^64) in which case it would not conserve uniqueness of the UUID

Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *