This might help!

Feb 19, 2012 at 2:14 AM

I finally got something built that can convert Decimal To Hex, Hex To Decimal, and Decimal To Binary, and Binary to Decimal. It works I have tried it. Enjoy!

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;
        }
By the way this does work in Cosmos without any problems.

Feb 20, 2012 at 2:44 PM
Edited Feb 20, 2012 at 2:45 PM

I don't think it does work, because it says 256 in hex is 0x121, when it is actually 0x100, and it gave me a negative number from a hex string.

Feb 20, 2012 at 7:23 PM
Aurora01 wrote:

I don't think it does work, because it says 256 in hex is 0x121, when it is actually 0x100, and it gave me a negative number from a hex string.

Yeah there was a issue with that one, if you check pear: pearos.codeplex.com under Core > PearMath > Conversions > ToAny you will see all of my code in there. =). Enjoy.