Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 2 Guids into string of max 50 characters length (2 way conversion)

Tags:

c#

.net

guid

base36

have an interesting problem - I need to convert 2 (randomly) generated Guids into a string. Here are the constraints:

  1. string max 50 charactes length.
  2. only numbers and small letters can be used (0123456789abcdefghijklmnopqrstuvwxyz)
  3. the algorithm has to be 2 way - need to be able to decode the encoded string into same 2 separate guids.

I've browsed a lot looking for toBase36 conversion bo so far no luck with Guid.

Any ideas? (C#)

like image 259
user1275154 Avatar asked Mar 17 '12 00:03

user1275154


1 Answers

First of all, you're in luck, 36^50 is around 2^258.5, so you can store the information in a 50 byte base-36 string. I wonder, though, why anybody would have to use base-36 for this.

You need to treat each GUID as a 128-bit number, then combine them into a 256-bit number, which you will then convert to a base-36 'number'. Converting back is doing the same in reverse.

Guid.ToByteArray will convert a GUID to a 16 byte array. Do it for both GUIDs and you have a 32 byte (which is 256 bits) array. Construct a BigInt from that array (there's a constructor), and then just convert that number to base-36.

To convert a number to base-36, do something like this (I assume everything is positive)

const string digits = "0123456789abcdefghijklmnopqrstuvwxyz";

string ConvertToBase36(BigInt number)
{
    string result = "";
    while(number > 0)
    {
        char digit = string[number % 36];
        result += digit;
        number /= 36;
    }
}
like image 152
zmbq Avatar answered Oct 14 '22 08:10

zmbq