Skip to content

Instantly share code, notes, and snippets.

@gfredericks
Last active December 17, 2015 11:29
Show Gist options
  • Save gfredericks/5602084 to your computer and use it in GitHub Desktop.
Save gfredericks/5602084 to your computer and use it in GitHub Desktop.
Converting a byte array to a UUID
(defn byte->long [b] (if (neg? b) (+ 256 b) b))
(defn bytes->long
[bytes]
{:pre [(= 8 (count bytes))]}
(apply + (map bit-shift-left (reverse (map byte->long bytes)) (range 0 64 8))))
(defn bytes->uuid
[bytes]
(java.util.UUID. (bytes->long (take 8 bytes))
(bytes->long (drop 8 bytes))))
;; usage
(def bytes (into-array Byte/TYPE [48 3 94 -5 34 -109 68 95 -97 -91 -110 42 43 52 119 -117]))
(bytes->uuid bytes)
;; => #uuid "30035efb-2293-445f-9fa5-922a2b34778b"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment