Advertisement
sashomaga

Convert hex to binary

Jan 18th, 2013
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.47 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. //Write a program to convert hexadecimal numbers to binary numbers (directly).
  5. class HexToBinary
  6. {
  7.     static void Main()
  8.     {
  9.         Console.WriteLine("Enter hex number : ");
  10.         string convert = Console.ReadLine();
  11.         convert = convert.ToLower();
  12.  
  13.         List<string> result = new List<string>();
  14.         int temp = 0;
  15.         for (int i = convert.Length - 1; i >= 0; i--)
  16.         {
  17.             temp = GetCharValue(convert, i);
  18.             result.Add(GetBinaryWord(temp));
  19.         }
  20.  
  21.         Console.WriteLine("Converted to binary:");
  22.         for (int i = result.Count - 1; i >= 0; i--)
  23.         {
  24.             Console.Write(result[i]);
  25.         }
  26.         Console.WriteLine();
  27.     }
  28.  
  29.     private static string GetBinaryWord(int temp)
  30.     {
  31.         StringBuilder builder = new StringBuilder();
  32.  
  33.         for (int j = 0; j < 4; j++)
  34.         {
  35.             if ((temp & 1) == 1)
  36.             {
  37.                 builder.Insert(0, 1);
  38.             }
  39.             else
  40.             {
  41.                 builder.Insert(0, 0);
  42.             }
  43.             temp /= 2;
  44.         }
  45.         return builder.ToString();
  46.     }
  47.  
  48.     private static int GetCharValue(string convert, int position)
  49.     {
  50.         if (convert[position] <= '9')
  51.         {
  52.             return convert[position] - '0';
  53.         }
  54.         else
  55.         {
  56.             return convert[position] - 'a' + 10;
  57.         }
  58.  
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement