CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Generate a unique ID from a Guid

267 Views
Copy Code Show/Hide Line Numbers
  /// <summary>
  /// Generates a unique Id as string
  /// </summary>
  /// <returns></returns>
  public static string GenerateUniqueId()
  {
      byte[] bytes = Guid.NewGuid().ToByteArray();
      return StringUtils.Base36Encode(BitConverter.ToInt64(bytes, 0));            
  }
 
 
static char[] base36CharArray = "0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray();            
  static string base36Chars = "0123456789abcdefghijklmnopqrstuvwxyz";
 
  /// <summary>
  /// Encodes an integer into a string by mapping to alpha and digits (36 chars)
  /// chars are embedded as lower case
  /// 
  /// Example: 4zx12ss
  /// </summary>
  /// <param name="value"></param>
  /// <returns></returns>
  public static string Base36Encode(long value)
  {
      string returnValue = "";
      bool isNegative = value < 0;
      if (isNegative)
          value = value * -1;
      
      do
      {
          returnValue = base36CharArray[value % base36CharArray.Length] + returnValue;
          value /= 36;
      } while (value != 0);
 
      return isNegative ? "-" + returnValue : returnValue;
  }
 
  /// <summary>
  /// Decodes a base36 encoded string to an integer
  /// </summary>
  /// <param name="input"></param>
  /// <returns></returns>
  public static long Base36Decode(string input)
  {
      bool isNegative = false;
      if (input.StartsWith("-"))
      {
          isNegative = true;
          input = input.Substring(1);
      }
 
      char[] arrInput = input.ToCharArray();
      Array.Reverse(arrInput);
      long returnValue = 0;
      for (long i = 0; i < arrInput.Length; i++)
      {
          long valueindex = base36Chars.IndexOf(arrInput[i]);
          returnValue += Convert.ToInt64(valueindex * Math.Pow(36, i));
      }
      return isNegative ? returnValue * -1 : returnValue;
  }
 
by Rick Strahl
  July 09, 2009 @ 2:23pm
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate