Ben Foster
Ben Foster

Reputation: 34800

Shortest possible encoding of Guid that guarantees uniqueness

Currently we are base 64 encoding our Guids when we need a unique url.

The question is, can we go shorter than 22 characters whilst guaranteeing uniqueness?:

        var id = Guid.NewGuid().ToByteArray();
        var idString = Convert.ToBase64String(id)
            .Replace("=", "")
            .Replace("+", "-")
            .Replace("/", "_");

Currently this will produce a string like TwfQfblSTEuF7rLabS2bjA

Upvotes: 2

Views: 904

Answers (2)

Hans Passant
Hans Passant

Reputation: 941465

Base64 encodes 6 bits per character. A guid has 128 bits. You'll thus need 128 / 6 = 21.33 characters. Can't do fractional, 22 is the hard lower limit. You can only get less characters by encoding more bits per char. That makes the URL encoding grotty, I can't think of a decent reason why you'd want to do that.

Upvotes: 3

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

Only ASCII characters (real ASCII, not anything with bytes >=128) are valid in URLs. Base64 is already quite close to the shortest URL representation for a string of bytes you can get. If you want to get really pedantic, you should be able to shave a character or two off by using all the URL valid characters instead of just 64 (there's 80-something in total).

I'd say just go with base64. It's close enough.

Upvotes: 1

Related Questions