Convert base-27 (or base-X) to base-10 in C #?

Is there a ready-made function that allows you to do basic transformations in C #? I want to convert from base 26 and base of base 27 numbers to base 10. I can do this on paper, but I'm not a very experienced programmer and most likely will not do it from scratch, if possible. Thank you

+4
source share
2 answers

There is a ready-made function for converting numbers from base 2, 8 or 16 to base 10 ( Convert.ToInt32 ). If you want to convert numbers from base 26 or base 27 to base 10, you will have to do it yourself.

Now I have never heard of 26 base numbers, so I'm just going to assume that the “numbers” are from A to Z (A has a value of 0, and Z has a decimal value of 25). To convert from base 26 to base 10, you must do the following:

 string charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int GetDigitValue(char digit) { return charset.IndexOf(digit); } int ConvertFromBase26(string number) { int result = 0; foreach(char digit in number) result = result * charset.Length + GetDigitValue(digit); return result; } 

To convert from base 27, simply add any character representing 26.

Note. There is no error correction (you can convert the string "$ # $@ # $@ ", which will bring you a nice negative number), and GetDigitValue is quite inefficient and should be replaced by a look-up table if you plan to do these conversions a lot.

EDIT: LINQ version, kick only.

Again, no effective search and lack of error correction if the string consists only of legal numbers.

 string charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int ConvertFromBase(string charset, string number) { return number.Select(c=>charset.IndexOf(c)).Aggregate(0, (x, y) => x*charset.Length +y); } 

I think the first version is more readable.

+3
source

Based on your answer. You don't need a character set search list because you can just use char ASCII values.

 int ConvertFromBase26(string number) { return number.Select(digit => (int)digit - 64).Aggregate(0, (x, y) => x * 26 + y); } 

I used this to convert the addresses of row columns to int while programming using Excel.

0
source

Source: https://habr.com/ru/post/1399684/


All Articles