Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Write a program to convert decimal numbers to their hexadecimal representation.*/
- using System;
- using System.Collections;
- using System.Text;
- public class Exercise03DecimalToHexadecimal
- {
- private static void Main()
- {
- char[] hexSymbols = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
- Stack temp = new Stack();
- StringBuilder hex = new StringBuilder();
- int num = int.Parse(Console.ReadLine());
- byte sign = 0;
- byte mod = 0;
- int index = 0;
- if (num < 0)
- {
- sign = 15;
- num *= -1;
- mod = 1;
- }
- while (num != 0)
- {
- index = sign - (num % 16) + mod;
- if (index == 16)
- {
- index = 0;
- mod = 1;
- }
- else
- {
- mod = 0;
- }
- temp.Push(hexSymbols[Math.Abs(index)]);
- num = num / 16;
- }
- hex.Append(hexSymbols[sign]);
- for (int i = 0; i < 8 - temp.Count; i++)
- {
- hex.Append(hexSymbols[sign]);
- }
- foreach (var item in temp)
- {
- hex.Append(item);
- }
- Console.WriteLine("0x" + hex + "\n\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement