Advertisement
hristo_bratanov

Convert hexadecimal to binary (directly)

Jan 17th, 2013
611
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.00 KB | None | 0 0
  1. using System;
  2.  
  3. class HexToBinary
  4. {
  5.     static void Main()
  6.     {
  7.         string hexadec = Console.ReadLine();
  8.         ConvertHexToBinary(hexadec);
  9.     }
  10.     static void ConvertHexToBinary(string input)
  11.     {
  12.         int len = input.Length;
  13.         int binary = 0;
  14.         int count = 0;
  15.         for (int i = len-1; i >= 0; i--, count++)
  16.         {
  17.             switch (input[i])
  18.             {
  19.                 case 'A':   binary = binary | (10 << 4*count); break;
  20.                 case 'B':   binary = binary | (11 << 4*count); break;
  21.                 case 'C':   binary = binary | (12 << 4*count); break;
  22.                 case 'D':   binary = binary | (13 << 4*count); break;
  23.                 case 'E':   binary = binary | (14 << 4*count); break;
  24.                 case 'F':   binary = binary | (15 << 4*count); break;
  25.                 default: binary = binary | ((input[i] - 48) << 4*count); break;
  26.             }
  27.         }
  28.         Console.WriteLine(Convert.ToString(binary, 2).PadLeft(32, '0'));
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement