C# Program to Convert Decimal to Hexadecimal
Convert.ToString(decimalNumber, 16) in C# to convert a decimal number to its hexadecimal string representation.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int decimalNumber = 255; string hexValue = Convert.ToString(decimalNumber, 16); Console.WriteLine(hexValue); } }
Dry Run
Let's trace the decimal number 255 through the code.
Input decimal number
decimalNumber = 255
Convert to hexadecimal string
hexValue = Convert.ToString(255, 16) => "ff"
Print the result
Output: ff
| decimalNumber | hexValue |
|---|---|
| 255 | ff |
Why This Works
Step 1: Using Convert.ToString method
The Convert.ToString method with base 16 converts the decimal number to a hexadecimal string automatically.
Step 2: Base 16 representation
Hexadecimal uses digits 0-9 and letters a-f to represent values from 0 to 15, so the method returns a string with these characters.
Step 3: Output the result
The program prints the hexadecimal string, which is the converted value of the decimal input.
Alternative Approaches
using System; class Program { static void Main() { int decimalNumber = 255; string hex = ""; int num = decimalNumber; char[] hexDigits = "0123456789abcdef".ToCharArray(); if (num == 0) hex = "0"; while (num > 0) { int remainder = num % 16; hex = hexDigits[remainder] + hex; num /= 16; } Console.WriteLine(hex); } }
using System; class Program { static void Main() { int decimalNumber = 255; string hexValue = decimalNumber.ToString("x"); Console.WriteLine(hexValue); } }
Complexity: O(log n) time, O(1) space
Time Complexity
Conversion depends on the number of digits in the hexadecimal representation, which is proportional to log base 16 of the decimal number.
Space Complexity
Only a small fixed amount of extra space is used for the output string and variables, so space is constant.
Which Approach is Fastest?
Using built-in methods like ToString("x") or Convert.ToString is fastest and simplest compared to manual conversion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Convert.ToString(decimal, 16) | O(log n) | O(1) | Quick and easy conversion |
| decimal.ToString("x") | O(log n) | O(1) | Most concise and readable |
| Manual division and remainder | O(log n) | O(1) | Learning how conversion works |
decimalNumber.ToString("x") for a concise way to convert decimal to hexadecimal.