Difference between revisions of "CSharp DecimalToBase"

From scripting
Jump to: navigation, search
(Created page with " public static string DecimalToBase(long Num, long Base) { const int BitsInLong = 64; const string Chars = "0123456789abcdefghijkLmn...")
 
(No difference)

Latest revision as of 05:01, 22 April 2017

        public static string DecimalToBase(long Num, long Base)
        {
            const int BitsInLong = 64;
            const string Chars = "0123456789abcdefghijkLmnopqrstuvwxyz";
            if (Base < 2 || Base > Chars.Length)
            {
                throw new ArgumentException("The base must be >= 2 and <= " +  
Chars.Length.ToString());
           }
            if (Num == 0)
            {
                return "0";
            }
            int index = BitsInLong - 1;
            long currentNum = Math.Abs(Num);
            char[] charArr = new char[BitsInLong];

            while (currentNum != 0)
            {
                int rem = (int)(currentNum % Base);
                charArr[index--] = Chars[rem];
                currentNum = currentNum / Base;
            } 

            string result = new string(charArr, index + 1, BitsInLong - index - 1);
            if (Num < 0)
            {
                result = "-" + result;
            }
            return result;
        }

This subroutine was used in the development of the Mega-Dots World's Toughest Connect-the-Dots Puzzles.

Unrelated MEL scripting help located here: YSYT.