Friday, November 12, 2010

Converting int to base26 string in C#...

For my own reference.
    public string ToBase26(int number)
    {
        char[] base26 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

        int remainder = number % base26.Length;
        int value = number / base26.Length;

        return value == 0 ?
            String.Format("{0}", base26[remainder]) :
            String.Format("{0}{1}", ToBase26(value - 1), base26[remainder]);
    }
Alternatively I can code it this way
    public string ToBase26(int number)
    {
        if (number < 0) return String.Empty;

        int remainder = number % 26;
        int value = number / 26;

        return value == 0 ?
            String.Format("{0}", Convert.ToChar(65 + remainder)) :
            String.Format("{0}{1}", ToBase26(value - 1), Convert.ToChar(65 + remainder));
    }

No comments:

Post a Comment