Return to Snippet

Revision: 9484
at November 9, 2008 19:05 by dreamlusion


Initial Code
using System;

namespace BaseConversion
{
    public static class BaseTransformations
    {
        private const int DecimalRadix = 10;
        private const int MaxBit = 32;
        private static char[] _hexChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        private static int[] _hexValues = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

        public static int BaseToDecimal(string completeHex, int radix)
        {
            int value = 0;
            int product = 1;
            for (int i = completeHex.Length - 1; i >= 0; i--, product = product * radix)
            {
                char hex = completeHex[i];
                int hexValue = -1;

                for (int j = 0; j < _hexChars.Length - 1; j++)
                {
                    if (_hexChars[j] == hex)
                    {
                        hexValue = _hexValues[j];
                        break;
                    }
                }

                value += (hexValue * product);
            }
            return value;
        }


        public static string DecimalToBase(int decimalValue, int radix)
        {
            string completeHex = "";
            
            int[] remainders = new int[MaxBit];
            int maxBit = MaxBit;

            for (; decimalValue > 0; decimalValue = decimalValue / radix)
            {
                maxBit = maxBit - 1;

                remainders[maxBit] = decimalValue % radix;
            }

            for (int i = 0; i < remainders.Length; i++)
            {
                int value = remainders[i];

                if (value >= DecimalRadix)
                {
                    completeHex += _hexChars[value % DecimalRadix];
                }
                else
                {
                    completeHex += value;
                }
            }

            completeHex = completeHex.TrimStart(new char[] { '0' });

            return completeHex;
        }
    }
}

Initial URL

                                

Initial Description
Description of the implementation can be found [here](http://pages.cs.wisc.edu/~markhill/cs354/Fall2008/notes/numbers.html).

Initial Title
Base Conversion Algorithm (Decimal to Hex, Decimal to Bin, Hex to Decimal, Bin to Decimal, e.t.c.)

Initial Tags

                                

Initial Language
C#