Skip to content

Instantly share code, notes, and snippets.

@daboxu
Last active May 27, 2024 18:38
Show Gist options
  • Save daboxu/4f1dd0a254326ac2361f8e78f89e97ae to your computer and use it in GitHub Desktop.
Save daboxu/4f1dd0a254326ac2361f8e78f89e97ae to your computer and use it in GitHub Desktop.
Convert GUID to byte array in Javascript

It is so painful for me when I found there is no code did such so simple thing on the Internet in a simple way. So I did it.

function guidToBytes(guid) {
    var bytes = [];
    guid.split('-').map((number, index) => {
        var bytesInChar = index < 3 ? number.match(/.{1,2}/g).reverse() :  number.match(/.{1,2}/g);
        bytesInChar.map((byte) => { bytes.push(parseInt(byte, 16));})
    });
    return bytes;
}

guid id format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX

@verystack
Copy link

You've literally just saved me hours. Thanks for this.

@will-malisch
Copy link

Agreed, thanks. This is great

@Kilowhisky
Copy link

Kilowhisky commented Dec 7, 2023

If you have access to Buffer() this is a one liner.

Buffer.from(guid.replace('-',''), 'hex')

EDIT: So fun fact, this one liner doesn't work!

C# and others don't encode GUID/UUID bytes the way its done visually. They actually change the endianness of the first few parts. Funny enough, this was accounted for in the code above!

@daboxu
Copy link
Author

daboxu commented Dec 19, 2023

If you have access to Buffer() this is a one liner.

Buffer.from(guid.replace('-',''), 'hex')

🔥 🔥 🔥

This was made in 2016 I bet there are more and better ways to deal with it now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment