Saturday, June 9, 2012

Custom Guid's

Caught a question from Stacy Draper, @StacyDraper this morning about custom guids, to make them more recognizable.

It reminded me of a post I saw recently about Facebook using hex characters to make IPv6 addresses more recognizable.

Here's what I was thinking... create a guid that has an embedded word.

For example, the following code creates a Guid that always starts with FACEB00C:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace CustomGuidTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Guid customGuid = GenerateCustomGuid();
            Console.WriteLine(customGuid.ToString("B"));
            Console.ReadKey();
        }
 
        static Guid GenerateCustomGuid()
        {
            Guid result;
 
            //0xFACEB00C
            //backwards, but required this to achieve desired result
            //Likely due to some standard with respect to bit order.
            byte[] custom = new byte[] { 0x0C, 0xB0, 0xCE, 0xFA  };

            byte[] random = Guid.NewGuid().ToByteArray();
            byte[] final = new byte[16];
            for (int idx = 0; idx <16; idx++)
            {
                if (idx >= custom.Length)
                {
                    final[idx] = random[idx];
                }
                else
                {
                    final[idx] = custom[idx];
                }
            }
            result = new Guid(final);
            return result;
        }
    }
}
Example output:
{faceb00c-7828-4e99-8cf5-280e33202670}
Post a Comment