Search code examples
c#base36

How to convert sum of ascii values of a string to base 36 in C#


In C# how can I convert the sum of ascii values of a string to base 36 ?

my string "P0123456789"

Thanks.


Solution

  • You can use

    var s = "P0123456789";
    var result = s.Sum(x => x);
    var base36ed = ConvertToBase(result,36);
    

    Output = GT

    The method below was found here

    public String ConvertToBase(int num, int nbase)
    {
    String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    // check if we can convert to another base
    if(nbase < 2 || nbase > chars.Length)
        return "";
    
    int r;
    String newNumber = "";
    
    // in r we have the offset of the char that was converted to the new base
    while(num >= nbase)
    {
        r = num % nbase;
        newNumber = chars[r] + newNumber;
        num = num / nbase;
    }
    // the last number to convert
    newNumber = chars[num] + newNumber;
    
    return newNumber;
    }