SHARE
TWEET

Exercise03DecimalToHexadecimal

g-stoyanov Jan 20th, 2013 153 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*Write a program to convert decimal numbers to their hexadecimal representation.*/
  2.  
  3. using System;
  4. using System.Collections;
  5. using System.Text;
  6.  
  7. public class Exercise03DecimalToHexadecimal
  8. {
  9.     private static void Main()
  10.     {
  11.         char[] hexSymbols = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  12.         Stack temp = new Stack();
  13.         StringBuilder hex = new StringBuilder();
  14.         int num = int.Parse(Console.ReadLine());
  15.         byte sign = 0;
  16.         byte mod = 0;
  17.         int index = 0;
  18.         if (num < 0)
  19.         {
  20.             sign = 15;
  21.             num *= -1;
  22.             mod = 1;
  23.         }
  24.  
  25.         while (num != 0)
  26.         {
  27.             index = sign - (num % 16) + mod;
  28.             if (index == 16)
  29.             {
  30.                 index = 0;
  31.                 mod = 1;
  32.             }
  33.             else
  34.             {
  35.                 mod = 0;
  36.             }
  37.  
  38.             temp.Push(hexSymbols[Math.Abs(index)]);
  39.             num = num / 16;
  40.         }
  41.  
  42.         hex.Append(hexSymbols[sign]);
  43.         for (int i = 0; i < 8 - temp.Count; i++)
  44.         {
  45.             hex.Append(hexSymbols[sign]);
  46.         }
  47.  
  48.         foreach (var item in temp)
  49.         {
  50.             hex.Append(item);
  51.         }
  52.  
  53.         Console.WriteLine("0x" + hex + "\n\n");
  54.     }
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top