Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace _03.DecimalToHex
- {
- class Program
- {
- static char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
- static void Main(string[] args)
- {
- int decimalNumber=-12345678;
- //Console.WriteLine("Enter decimal number: ");
- //decimalNumber = int.Parse(Console.ReadLine());
- bool isNegative = decimalNumber < 0 ? true : false;
- string hexNumber = ToHex(decimalNumber, isNegative);
- Console.WriteLine(hexNumber);
- }
- private static string ToHex(int decimalNumber, bool isNegative)
- {
- StringBuilder result = new StringBuilder();
- if (isNegative)
- {
- decimalNumber *= -1; //get the positive value
- //get the length of the bits in decimalNumber without left zeroes
- int length = Convert.ToString(decimalNumber,2).Length;
- //we have to split the binary code by 4 bits
- int addition=0;
- if (length%4 !=0)
- {
- //get the difference between length and 4 if it doesn't devide exactly
- addition = 4 - length % 4;
- }
- int lengthBits = length + addition;
- //if the bits aren't exactly lengthBits we fill with zeroes from the left
- string bits = Convert.ToString(decimalNumber,2);
- //we get the new decimalNumber
- decimalNumber = Convert.ToInt32(bits, 2);
- //invert the bits till lengthbits with the XOR operator
- int mask = 1;
- for (int i = 0; i < lengthBits; i++)
- {
- mask = 1<<i;
- decimalNumber = decimalNumber ^ mask;
- }
- //we add + 1
- decimalNumber += 1;
- }
- while (decimalNumber != 0)
- {
- //match the remaining with the coresponding element in the hex array
- result.Append(hexArray[decimalNumber % 16]);
- decimalNumber /= 16;
- }
- string hex = result.ToString();
- int lengthHex = hex.Length;
- result.Clear();
- //reverse the array in the right way
- for (int i = lengthHex-1; i >= 0; i--)
- {
- result.Append(hex[i]);
- }
- if (isNegative)
- {
- hex = result.ToString();
- result.Clear();
- //fill the left spaces with F
- result.Append(hex.PadLeft(8,'F'));
- }
- return result.ToString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement