Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace _02.ConvertBinaryToDecimal
- {
- class Program
- {
- // 02. Write a program to convert binary numbers to their decimal representation.
- static string ReadDecimalInput()
- {
- string input = "";
- bool boolean = true;
- while (boolean)
- {
- boolean = false;
- Console.Write("Insert binary number: ");
- input = Console.ReadLine();
- if (input.Length <= 32 && input != "")
- {
- for (byte i = 0; i < input.Length; i++)
- {
- if (input[i] == '0' || input[i] == '1')
- {
- }
- else
- {
- boolean = true;
- input = "";
- Console.WriteLine("Incorect input! Only '1' amd '0' allowed!");
- break;
- }
- }
- }
- else if (input == "")
- {
- Console.WriteLine("Empty input!");
- boolean = true;
- }
- else
- {
- Console.WriteLine("Incorect input! No more that 32 digits!");
- boolean = true;
- }
- }
- return input;
- }
- static void BinaryToDecimal(string input)
- {
- int decNum = 0;
- if (input.Length == 32 && input[0] == '1') // negative
- {
- int j = input.Length - 2;
- int parse = 0;
- for (int i = 1; i < input.Length; i++, j--) // start from input[1] because input[0] holds the sign
- {
- parse = int.Parse(input[i].ToString());
- if (parse == 0)
- {
- decNum += 1 * (int)Math.Pow(2, j);
- }
- }
- decNum = -decNum - 1;
- }
- else // positive
- {
- int j = input.Length - 1;
- int i = 0;
- int parse = 0;
- for (i = 0; i < input.Length; i++, j--)
- {
- parse = int.Parse(input[i].ToString());
- if (parse == 1)
- {
- decNum += 1 * (int)Math.Pow(2, j);
- }
- }
- }
- Console.WriteLine(decNum);
- }
- static void Main(string[] args)
- {
- while (true)
- {
- string input = ReadDecimalInput();
- BinaryToDecimal(input);
- // check
- int n = Convert.ToInt32(input, 2);
- Console.WriteLine(n);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement