Skip to content

Instantly share code, notes, and snippets.

@novabyte
Created October 16, 2017 11:45
Show Gist options
  • Save novabyte/672ec549635eaccbc401b442d7a52bd8 to your computer and use it in GitHub Desktop.
Save novabyte/672ec549635eaccbc401b442d7a52bd8 to your computer and use it in GitHub Desktop.
A helper class to convert UUIDv4 strings into bytes and back again with C#.
using System;
public class UUID
{
public static byte[] FromString(string uuid)
{
var guid = new Guid(uuid).ToByteArray();
Array.Reverse(guid, 6, 2);
Array.Reverse(guid, 4, 2);
Array.Reverse(guid, 0, 4);
return guid;
}
public static string FromBytes(byte[] uuid)
{
Array.Reverse(uuid, 0, 4);
Array.Reverse(uuid, 4, 2);
Array.Reverse(uuid, 6, 2);
return new Guid(uuid).ToString();
}
}
@novabyte
Copy link
Author

Usage example:

var session = "e6e11936-1ed2-4d8b-809d-79a1ae4a7e9b";
byte[] uuid = UUID.FromString(session);
string sout = UUID.FromBytes(uuid);
System.Console.WriteLine(string.Equals(session, sout));

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