ellapt

T10.7.ConvertAnyToAny

Jan 22nd, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. using System;
  2.  
  3. class ConvertAnyToAny
  4. {
  5. //************** Convert the number numInX from numeral system of base X ********************//
  6. //************** to any other numeral system of base Y (2 ≤ s, d ≤ 16) ********************//
  7. static string FromXtoY(string numInX, int baseX, int baseY)
  8. {
  9. int numInDecimal = BaseXToBase10(numInX, baseX); // convert a number n from base X to decimal
  10. string result=FromDecimalToX(numInDecimal, baseY); // convert a number from decimal to base X
  11. return result;
  12. }
  13.  
  14. // Convert a decimal number to a number of base Y
  15. static string FromDecimalToX(int numDec, int yBase)
  16. {
  17. string numInX = "";
  18. char nextChar;
  19.  
  20. while (numDec != 0)
  21. {
  22. int residue=numDec % yBase;
  23. if ((residue) >= 10)
  24. {
  25. nextChar = (char)('A' + residue - 10);
  26. }
  27. else
  28. {
  29. nextChar = (char)(char)('0' + residue);
  30. }
  31. numInX = nextChar + numInX;
  32. numDec /= yBase;
  33. }
  34. return numInX;
  35. }
  36.  
  37. // Convert a number of base X to decimal
  38. static int BaseXToBase10(string numX, int s)
  39. {
  40. int numDec = 0;
  41. int num=0;
  42. int pos = 1;
  43. for (int i = numX.Length - 1; i >= 0; i--)
  44. {
  45. if (numX[i] >= 'A')
  46. {
  47. num = numX[i] - 'A' + 10;
  48. }
  49. else
  50. {
  51. num= numX[i] - '0';
  52. }
  53. numDec += num * pos;
  54. pos *= s;
  55. }
  56. return numDec;
  57. }
  58.  
  59. static void Main()
  60. {
  61. Console.WriteLine("Convert from any numeral system of given base s");
  62. Console.WriteLine("to any other numeral system of base d (2 ≤ s, d ≤ 16)\n");
  63. Console.WriteLine(FromXtoY("7777", 8, 16));
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment