/ Published in: C#
Description of the implementation can be found [here](http://pages.cs.wisc.edu/~markhill/cs354/Fall2008/notes/numbers.html).
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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 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; } } return completeHex; } } }