I needed to create a simple method that converts numbers in Base 26 (string
) using, as expected, letters from a to z.
But that's not all, this Base 26 needs to be One Based. Which means that there is no representation for zero absolute value and there is a representation for 26 absolute value. Let me show a example:
In Base 26 Zero Based the number 18252 will be represented like:
$$ (18252)_{10} = (BBAA)_{26} $$
where B == 1
and A == 0
. But as an One Based I need to get:
$$ (18252)_{10} = (ZYZ)_{26} $$
where Y == 25
and Z == 26
.
So I came up with this snippet:
var array = new List<int>();
var div = myNumber;
var getOne = 0;
while (div > 26)
{
var value = div % 26;
value -= getOne;
if (value <= 0)
{
value += 26;
getOne = 1;
}
else
{
getOne = 0;
}
array.Add(value);
div = div / 26;
}
div -= getOne;
if (div > 0) array.Add(div);
var letters = array.Select(s => (char)('A' + s - 1)).Reverse().ToArray();
return new string(letters);
Now I wonder if there is a better way write this.