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

1

6

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#)

Leanoraleant answered 17/3, 2012 at 0:43 Comment(1)
Found a solution codeproject.com/Articles/16035/…Leanoraleant
F
10

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;
    }
}
Footlocker answered 17/3, 2012 at 0:53 Comment(3)
thanks for that! How do I convert BigInt to base-36? That is what I'm struggling with...Leanoraleant
I don't understand how this works. RESULT is null. So you are running a modulus on a null value each and every time through the loop. This means your result will be null.Sharkskin
You found a typo. It should say number % 36.Footlocker

© 2022 - 2024 — McMap. All rights reserved.