0% found this document useful (0 votes)
38 views

Converting Decimal Number Into Hexadecimal Number in Visual C

This document describes a method in Visual C# 2005 to convert a positive decimal number between 0 and 2^16 to a hexadecimal number. The method divides the decimal number by successive powers of 16, takes the integer quotient of each division, converts it to a hexadecimal digit, and concatenates the digits into a string, omitting leading zeros. It uses a helper method to map integer quotients 0-15 to the corresponding hexadecimal characters.

Uploaded by

yehiely
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Converting Decimal Number Into Hexadecimal Number in Visual C

This document describes a method in Visual C# 2005 to convert a positive decimal number between 0 and 2^16 to a hexadecimal number. The method divides the decimal number by successive powers of 16, takes the integer quotient of each division, converts it to a hexadecimal digit, and concatenates the digits into a string, omitting leading zeros. It uses a helper method to map integer quotients 0-15 to the corresponding hexadecimal characters.

Uploaded by

yehiely
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

Converting decimal number into hexadecimal number in Visual C# 2005

The following method will convert positive integer in the range of 0-2^16 to hexadecimal
number.

public static string DecToHex(double Input)


{
string hexResult=String.Empty;
bool start=false;
for (int i = 15; i >= 0; i--)
{
int quotient =Convert.ToInt32(Math.Floor(Input / Math.Pow(16, i)));
Input = Input - (quotient * Math.Pow(16, i));
if (DigitLetter(quotient) != "0")
start = true;
if (start)
hexResult += DigitLetter(quotient);
}
return hexResult;
}

Method will start to divide argument ‘Input’ by 2^15 and convert the integer part of the
quotient to a hexadecimal digit. Then, the product of quotient and 2^15 will be subtracted
from ‘Input’ and difference will be used as new dividend to be divided in 2^14 and so on…
When a first non-zero digit will be detected, variable ‘start’ will turn to TRUE and
hexadecimal digits will be accumulated. Thus, leading zeroes will not be displayed.

Method will utilize additional method DigitLetter that will obtain integer between 0-15
and return its hexadecimal value:

private static string DigitLetter(int In)


{
if (In < 10)
return In.ToString();
else if (In == 10)
return "A";
else if (In == 11)
return "B";
else if (In == 12)
return "C";
else if (In == 13)
return "D";
else if (In == 14)
return "E";
else if (In == 15)
return "F";
else return "X";
}

You might also like