Skip to content

Latest commit

 

History

History
83 lines (61 loc) · 1.83 KB

id-generation-and-encoding.md

File metadata and controls

83 lines (61 loc) · 1.83 KB

Id Generation and Encoding

How to generate and encode an id into a fixed 11-length string of characters:


  • Example:
Id Encoded Id
1034467521726252594 9NJCx7XUMmo



  1. Generate a random unsigned long number
    • between min and max
ulong _min = (ulong)Math.Pow(2, 10);
ulong _max = ulong.MaxValue - 1;
var id = Utils.GenerateRandomUlongNumber(_min, _max);

The GenerateRandomUlongNumber method:

private static readonly Random _random = new Random();

public static ulong GenerateRandomUlongNumber(ulong min, ulong max)
{
    ulong uRange = (max - min);
    ulong ulongRand;
    do
    {
        byte[] buf = new byte[8];
        _random.NextBytes(buf);
        ulongRand = BitConverter.ToUInt64(buf, 0);
    } while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange);

    return (ulongRand % uRange) + min;
}

  1. Get bytes of the number
var bytes = BitConverter.GetBytes(id);

  1. Encode the bytes with a base58 mapper
var encodedId = Base58.Bitcoin.Encode(bytes);
  • Why Base58?

Just like a bitcoin address:

Note: the non-alphanumeric characters in base-64 is "+" and "/"



  1. I also added some filters
// To filter 10-length encoded ids
if (id % 256 < 6)
	return false;

// To filter encoded ids which has three same characters in a row
Regex _encodedIdWrongRepetitionRegex = new(@"(\S)\1{2}");
if (_encodedIdWrongRepetitionRegex.IsMatch(encodedId))
	return false;

Check the IdGenerator class