Advertisement
hristo_bratanov

Convert binary to hexadecimal (directly)

Jan 17th, 2013
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2.  
  3. class BinaryToHexadecimal
  4. {
  5.     static void Main()
  6.     {
  7.         string binary = Console.ReadLine();
  8.         ConvertBinarToHex(binary);
  9.         Console.WriteLine();
  10.     }
  11.  
  12.     static void ConvertBinarToHex(string input)
  13.     {
  14.         int len = input.Length;
  15.         int steps = 0;
  16.         int reminder = len % 4;
  17.         int inputBinaryLength = len + (4 - reminder);
  18.         if (reminder != 0)
  19.         {
  20.             steps = len/4 + 1;
  21.         }
  22.         else
  23.         {
  24.             steps = len/4;
  25.         }
  26.         int sum = 0;
  27.         int startSearch = 0;
  28.         int endSearch = 0;
  29.         int rank = 0;
  30.         for (int i = 0; i < steps; i++)
  31.         {
  32.             if (i == 0)
  33.             {
  34.                 startSearch = 0;
  35.                 endSearch = reminder;
  36.             }
  37.             else if (i == 1)
  38.             {
  39.                 startSearch = reminder;
  40.                 endSearch = reminder + 4;
  41.             }
  42.             else
  43.             {
  44.                 startSearch = endSearch;
  45.                 endSearch = startSearch + 4;
  46.                
  47.             }
  48.             rank = endSearch - startSearch - 1;
  49.             for (int j = startSearch; j < endSearch; j++, rank--)
  50.             {
  51.                 sum = sum + (int)((input[j]-48)*(Math.Pow(2, rank)));
  52.             }
  53.             switch (sum)
  54.             {
  55.                 case 10: Console.Write("A"); break;
  56.                 case 11: Console.Write("B"); break;
  57.                 case 12: Console.Write("C"); break;
  58.                 case 13: Console.Write("D"); break;
  59.                 case 14: Console.Write("E"); break;
  60.                 case 15: Console.Write("F"); break;
  61.                 default: Console.Write(sum); break;
  62.             }
  63.             rank = 0;
  64.             sum = 0;
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement