Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- //Write a program to convert hexadecimal numbers to binary numbers (directly).
- class HexToBinary
- {
- static void Main()
- {
- Console.WriteLine("Enter hex number : ");
- string convert = Console.ReadLine();
- convert = convert.ToLower();
- List<string> result = new List<string>();
- int temp = 0;
- for (int i = convert.Length - 1; i >= 0; i--)
- {
- temp = GetCharValue(convert, i);
- result.Add(GetBinaryWord(temp));
- }
- Console.WriteLine("Converted to binary:");
- for (int i = result.Count - 1; i >= 0; i--)
- {
- Console.Write(result[i]);
- }
- Console.WriteLine();
- }
- private static string GetBinaryWord(int temp)
- {
- StringBuilder builder = new StringBuilder();
- for (int j = 0; j < 4; j++)
- {
- if ((temp & 1) == 1)
- {
- builder.Insert(0, 1);
- }
- else
- {
- builder.Insert(0, 0);
- }
- temp /= 2;
- }
- return builder.ToString();
- }
- private static int GetCharValue(string convert, int position)
- {
- if (convert[position] <= '9')
- {
- return convert[position] - '0';
- }
- else
- {
- return convert[position] - 'a' + 10;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement