Converting between java.util.UUID and byte[]

UUIDs?

Universally Unique IDentifiers (UUIDs) are standard identifiers commonly used in distributed systems where guaranteed item id uniqueness is needed. They are 128-bit long identifiers generated using one of couple of possible generation mechanisms. UUIDs are transferred either as native 128-bit binary types or as 36-character long textual representations (32 hex digits, 4 hyphens separating 5 groups of digits).

JDK has type java.util.UUID to represent these identifiers: the class supports construction of instances from String, serialization of instances as Strings and generation using some (but not all) of the standard mechanisms (specifically: the random-number based variant that is usually used).

But while use of String representation works well for many use cases (such as APIs that uses textual formats like REST APIs and GraphQL), in many cases the more compact binary representation makes more sense.
java.util.UUID unfortunately offers no support for converting between UUIDs and byte[] or ByteBuffer.

UUID in Java beyond java.util.UUID

So java.util.UUID is a bit of bare-bones class for basic UUID handling.
For full set of things there exist multiple Java UUID libraries: most notably java-uuid-generator (“JUG”) that I originally wrote almost 20 years ago (and have maintained since then).
(note: creation of java-uuid-generator predates addition of java.util.UUID by 2 years — so support for java.util.UUID in JUG happened in version 3.0!)

One of more notable things missing from JDK version is the ability use “date-time” based generation mechanism over random-number generator based one:

UUID uuid = Generators.timeBasedGenerator().generate();

There are also some performance benefits from using JUG over methods in java.util.UUID: conversions to/from String in JDK have traditionally not been well optimized (see “Measuring performance of Java UUID.fromString()”).

But as I mentioned earlier, there is yet another rather common set of operations that is curiously absent from JDK: converting between 128-bit binary representation and java.util.UUID (note: it is possible to write converters using UUID.getLeastSignificantBits(), UUID.getMostSignificantBits() and UUID(long, long) constructors — but this is lot of boilerplate code).

Fortunately JUG has these user cases covered. Let’s have a look.

Constructing java.util.UUID from byte[] using JUG

Since JUG uses java.util.UUID as the UUID type, it cannot offer direct methods but instead has helper class UUIDUtil to contain methods needed. Constructing a UUID value works like this:

byte[] rawUuidBytes = ...; // byte array with 16 bytes
UUID uuidFromBytes = UUIDUtil.uuid(rawUuidBytes);
// or, if not 0-offset:
UUID uuid2 = UUIDUtil.uuid(rawUuidBytes, offset);

as expected.

Serializing java.util.UUID as byte[]

Similarly, UUIDUtil is used for serialization side as well:

byte[] asBytes = UUIDUtil.asByteArray(uuidFromBytes);
// or, if using an existing buffer
byte[] outputBuffer = new byte[1000];
// append at position #100
UUIDUtil.toByteArray(uuid, outputBuffer, 100);

Faster from-String conversion

Aside from these “missing methods” it may also make sense to use likely more efficient (*) methods for converting between java.lang.String
and java.util.UUID:

UUID uuidFromStr = UUIDUtil.uuid("ebb8e8fe-b1b1-11d7-8adb-00b0d078fa18");

There is currently no matching helper method for serializing UUID as String: for this operation standard UUID.toString() appears useful — although it would probably make sense to offer a method for serializing UUID into char[] buffer or Writer. Perhaps I’ll add some new functionality for java-uuid-generator’s 20th birthday :)

(*) Likely since later versions of JDK have apparently optimized these conversions more — I hope to investigate this angle a bit more in future!

--

--

--

Open Source developer, most known for Jackson data processor (nee “JSON library”), author of many, many other OSS libraries for Java, from ClassMate to Woodstox

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Run GUI Application inside Docker Container

Snowflake UDFs for Hash Validation, Part 2: Java

Implement a Very Simple Hashmap with C

How to limit Firestore queries with strict rules

Organizing your dotfiles

[Guide] How to host a static website for FREE using AWS S3

STRUCTURE OF A C PROGRAM

Lighthouse Testing tool — 2 : Lighthouse Report

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
@cowtowncoder

@cowtowncoder

Open Source developer, most known for Jackson data processor (nee “JSON library”), author of many, many other OSS libraries for Java, from ClassMate to Woodstox

More from Medium

How much memory does a Java server actually need? (Part 3/3)

A tentative comparison of fault tolerance libraries on the JVM

Configuring Spring Boot’s Server, GZip compression, HTTP/2, caching and much more

Java Reactive Solutions — My impressions on Spring,Quarkus,Jooby and VertX