Advertisement
JavaFan

Binary to Decimal INT

Jan 5th, 2014
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.06 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace _02.ConvertBinaryToDecimal
  8. {
  9. class Program
  10. {
  11. // 02. Write a program to convert binary numbers to their decimal representation.
  12.  
  13. static string ReadDecimalInput()
  14. {
  15. string input = "";
  16. bool boolean = true;
  17. while (boolean)
  18. {
  19. boolean = false;
  20. Console.Write("Insert binary number: ");
  21. input = Console.ReadLine();
  22. if (input.Length <= 32 && input != "")
  23. {
  24. for (byte i = 0; i < input.Length; i++)
  25. {
  26. if (input[i] == '0' || input[i] == '1')
  27. {
  28. }
  29. else
  30. {
  31. boolean = true;
  32. input = "";
  33. Console.WriteLine("Incorect input! Only '1' amd '0' allowed!");
  34. break;
  35. }
  36. }
  37. }
  38. else if (input == "")
  39. {
  40. Console.WriteLine("Empty input!");
  41. boolean = true;
  42. }
  43. else
  44. {
  45. Console.WriteLine("Incorect input! No more that 32 digits!");
  46. boolean = true;
  47. }
  48. }
  49.  
  50. return input;
  51. }
  52.  
  53. static void BinaryToDecimal(string input)
  54. {
  55. int decNum = 0;
  56.  
  57. if (input.Length == 32 && input[0] == '1') // negative
  58. {
  59. int j = input.Length - 2;
  60. int parse = 0;
  61.  
  62. for (int i = 1; i < input.Length; i++, j--) // start from input[1] because input[0] holds the sign
  63. {
  64. parse = int.Parse(input[i].ToString());
  65. if (parse == 0)
  66. {
  67. decNum += 1 * (int)Math.Pow(2, j);
  68. }
  69. }
  70. decNum = -decNum - 1;
  71.  
  72. }
  73. else // positive
  74. {
  75. int j = input.Length - 1;
  76. int i = 0;
  77. int parse = 0;
  78.  
  79. for (i = 0; i < input.Length; i++, j--)
  80. {
  81. parse = int.Parse(input[i].ToString());
  82. if (parse == 1)
  83. {
  84. decNum += 1 * (int)Math.Pow(2, j);
  85. }
  86. }
  87. }
  88. Console.WriteLine(decNum);
  89.  
  90.  
  91. }
  92.  
  93. static void Main(string[] args)
  94. {
  95. while (true)
  96. {
  97. string input = ReadDecimalInput();
  98.  
  99. BinaryToDecimal(input);
  100.  
  101. // check
  102. int n = Convert.ToInt32(input, 2);
  103. Console.WriteLine(n);
  104. }
  105. }
  106. }
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement