Home > other >  How would one convert a ULID type to UUID type?
How would one convert a ULID type to UUID type?

Time:12-16

I'm looking at this ULID generator https://wvlet.org/airframe/docs/airframe-ulid but am not quite sure how to convert the ULID to UUID. I've tried the below code expecting the first 48 bits to look alike but the bits appear random

scala> import java.util.UUID
scala> import wvlet.airframe.ulid.ULID
scala> (0 to 100).map(_ => UUID.nameUUIDFromBytes(ULID.newULID.toBytes))

val res36: IndexedSeq[java.util.UUID] = Vector(3d938b6f-167d-3915-9491-ca20400efc24, 72b562fa-7866-3401-ae8d-10fabf43864d, b60d0802-bf77-3cc3-a3de-fc1943fcdd8c, 4189103e-f284-3da3-a4ac-f43381197e64, c58829d6-31dc-33ed-accb-c76022b85f05, 765ed5fb-9542-332b-8ae7-eb00a4a4e313, a2fcbfd9-28be-374d-b7bc-97ade744e0f5, 50056d54-2eb7-3a50-bc91-ccbf279ef989, b49b8a86-ab8c-3e82-b06e-00460a5b600b, bb965b65-03bb-3785-a77b-4a858f190de1, 47e980bc-48b0-37ed-8d39-af3769f7758a, 57cf5eae-996b-3f1a-a24f-2594287f9c83, be38a6f3-df4d-31e5-9521-0078526fb6a5, fb1fa782-311d-322f-b902-ddf318f971c6, b64c5980-624e-3ea6-8813-94f8329fec32, 4c368e3d-3448-3d56-b8bd-abd84bc62d8a, aad5500b-720a-3445-8b06-e0e5b721ee5f, fb774e2c-9966-33be-bc59-6e88cd095178, 8265102b-e8fe-381f-bd51-49660dd63c13, 6b...

CodePudding user response:

Untested and not very clean:

import java.util.UUID
import wvlet.airframe.ulid.{ULID, CrockfordBase32}

val ulid = ULID.newULID
val (hi, lo) = CrockfordBase32.decode128bits(ulid.toString)
val uuid = new UUID(hi, lo)

UUID doesn't have a constructor that converts a 16 byte array to a UUID. You need to convert your array to 2 longs (2x 8 bytes).

  • Related