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


/ Published in: C#
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. using System;
  2.  
  3. namespace BaseConversion
  4. {
  5. public static class BaseTransformations
  6. {
  7. private const int DecimalRadix = 10;
  8. private const int MaxBit = 32;
  9. private static char[] _hexChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  10. private static int[] _hexValues = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
  11.  
  12. public static int BaseToDecimal(string completeHex, int radix)
  13. {
  14. int value = 0;
  15. int product = 1;
  16. for (int i = completeHex.Length - 1; i >= 0; i--, product = product * radix)
  17. {
  18. char hex = completeHex[i];
  19. int hexValue = -1;
  20.  
  21. for (int j = 0; j < _hexChars.Length - 1; j++)
  22. {
  23. if (_hexChars[j] == hex)
  24. {
  25. hexValue = _hexValues[j];
  26. break;
  27. }
  28. }
  29.  
  30. value += (hexValue * product);
  31. }
  32. return value;
  33. }
  34.  
  35.  
  36. public static string DecimalToBase(int decimalValue, int radix)
  37. {
  38. string completeHex = "";
  39.  
  40. int[] remainders = new int[MaxBit];
  41. int maxBit = MaxBit;
  42.  
  43. for (; decimalValue > 0; decimalValue = decimalValue / radix)
  44. {
  45. maxBit = maxBit - 1;
  46.  
  47. remainders[maxBit] = decimalValue % radix;
  48. }
  49.  
  50. for (int i = 0; i < remainders.Length; i++)
  51. {
  52. int value = remainders[i];
  53.  
  54. if (value >= DecimalRadix)
  55. {
  56. completeHex += _hexChars[value % DecimalRadix];
  57. }
  58. else
  59. {
  60. completeHex += value;
  61. }
  62. }
  63.  
  64. completeHex = completeHex.TrimStart(new char[] { '0' });
  65.  
  66. return completeHex;
  67. }
  68. }
  69. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.