Program for decimal to hexadecimal conversion
Last Updated :
30 Jul, 2024
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16.
Hexadecimal numbers use 16 values to represent a number. Numbers from 0-9 are expressed by digits 0-9 and 10-15 are represented by characters from A - F.
Examples:
Input : 116
Output: 74
Input : 10
Output: A
Input : 33
Output: 21
Algorithm:
- Store the remainder when the number is divided by 16 in a temporary variable temp. If the temp is less than 10, insert (48 + temp) in a character array otherwise if the temp is greater than or equal to 10, insert (55 + temp) in the character array.
- Divide the number by 16 now
- Repeat the above two steps until the number is not equal to 0.
- Print the array in reverse order now.
Example
If the given decimal number is 2545.
Step 1: Calculate the remainder when 2545 is divided by 16 is 1. Therefore, temp = 1. As temp is less than 10. So, arr[0] = 48 + 1 = 49 = '1'.
Step 2: Divide 2545 by 16. The new number is 2545/16 = 159.
Step 3: Calculate the remainder when 159 is divided by 16 is 15. Therefore, temp = 15. As temp is greater than 10. So, arr[1] = 55 + 15 = 70 = 'F'.
Step 4: Divide 159 by 16. The new number is 159/16 = 9.
Step 5: Calculate the remainder when 9 is divided by 16 is 9. Therefore, temp = 9. As temp is less than 10. So, arr[2] = 48 + 9 = 57 = '9'.
Step 6: Divide 9 by 16. The new number is 9/16 = 0.
Step 7: Since the number becomes = 0. Stop repeating steps and print the array in reverse order. Therefore, the equivalent hexadecimal number is 9F1.
The below diagram shows an example of converting the decimal number 2545 to an equivalent hexadecimal number.

Below is the implementation of the above idea.
C++
// C++ program to convert a decimal
// number to hexadecimal number
#include <iostream>
using namespace std;
// function to convert decimal to hexadecimal
string decToHexa(int n)
{
// ans string to store hexadecimal number
string ans = "";
while (n != 0) {
// remainder variable to store remainder
int rem = 0;
// ch variable to store each character
char ch;
// storing remainder in rem variable.
rem = n % 16;
// check if temp < 10
if (rem < 10) {
ch = rem + 48;
}
else {
ch = rem + 55;
}
// updating the ans string with the character variable
ans += ch;
n = n / 16;
}
// reversing the ans string to get the final result
int i = 0, j = ans.size() - 1;
while(i <= j)
{
swap(ans[i], ans[j]);
i++;
j--;
}
return ans;
}
// Driver code
int main()
{
int n = 2545;
cout << decToHexa(n);
return 0;
}
Java
// Java program to convert a decimal
// number to hexadecimal number
import java.io.*;
class GFG {
// function to convert decimal to hexadecimal
static void decToHexa(int n)
{
// char array to store hexadecimal number
char[] hexaDeciNum = new char[100];
// counter for hexadecimal number array
int i = 0;
while (n != 0) {
// temporary variable to store remainder
int temp = 0;
// storing remainder in temp variable.
temp = n % 16;
// check if temp < 10
if (temp < 10) {
hexaDeciNum[i] = (char)(temp + 48);
i++;
}
else {
hexaDeciNum[i] = (char)(temp + 55);
i++;
}
n = n / 16;
}
// printing hexadecimal number array in reverse
// order
for (int j = i - 1; j >= 0; j--)
System.out.print(hexaDeciNum[j]);
}
// driver program
public static void main(String[] args)
{
int n = 2545;
decToHexa(n);
}
}
// Contributed by Pramod Kumar
Python
# Python3 program to
# convert a decimal
# number to hexadecimal
# number
# function to convert
# decimal to hexadecimal
def decToHexa(n):
# char array to store
# hexadecimal number
hexaDeciNum = ['0'] * 100
# counter for hexadecimal
# number array
i = 0
while(n != 0):
# temporary variable
# to store remainder
temp = 0
# storing remainder
# in temp variable.
temp = n % 16
# check if temp < 10
if(temp < 10):
hexaDeciNum[i] = chr(temp + 48)
i = i + 1
else:
hexaDeciNum[i] = chr(temp + 55)
i = i + 1
n = int(n / 16)
# printing hexadecimal number
# array in reverse order
j = i - 1
while(j >= 0):
print((hexaDeciNum[j]), end="")
j = j - 1
# Driver Code
n = 2545
decToHexa(n)
# This code is contributed
# by mits.
C#
// C# program to convert a decimal
// number to hexadecimal number
using System;
class GFG {
// function to convert decimal
// to hexadecimal
static void decToHexa(int n)
{
// char array to store
// hexadecimal number
char[] hexaDeciNum = new char[100];
// counter for hexadecimal number array
int i = 0;
while (n != 0) {
// temporary variable to
// store remainder
int temp = 0;
// storing remainder in temp
// variable.
temp = n % 16;
// check if temp < 10
if (temp < 10) {
hexaDeciNum[i] = (char)(temp + 48);
i++;
}
else {
hexaDeciNum[i] = (char)(temp + 55);
i++;
}
n = n / 16;
}
// printing hexadecimal number
// array in reverse order
for (int j = i - 1; j >= 0; j--)
Console.Write(hexaDeciNum[j]);
}
// Driver Code
public static void Main(String[] args)
{
int n = 2545;
decToHexa(n);
}
}
// This code is contributed by Nitin Mittal.
JavaScript
<script>
// Javascript program to convert a decimal
// number to hexadecimal number
// function to convert decimal to hexadecimal
function decToHexa(n)
{
// char array to store hexadecimal number
var hexaDeciNum = Array.from({length: 100},
(_, i) => 0);
// counter for hexadecimal number array
var i = 0;
while (n != 0) {
// temporary variable to store remainder
var temp = 0;
// storing remainder in temp variable.
temp = n % 16;
// check if temp < 10
if (temp < 10) {
hexaDeciNum[i] =
String.fromCharCode(temp + 48);
i++;
}
else {
hexaDeciNum[i] =
String.fromCharCode(temp + 55);
i++;
}
n = parseInt(n / 16);
}
// printing hexadecimal number array in reverse
// order
for (j = i - 1; j >= 0; j--)
document.write(hexaDeciNum[j]);
}
// driver program
var n = 2545;
decToHexa(n);
// This code contributed by shikhasingrajput
</script>
PHP
<?php
// PHP program to convert
// a decimal number to
// hexadecimal number
// function to convert
// decimal to hexadecimal
function decToHexa($n)
{
// char array to store
// hexadecimal number
$hexaDeciNum;
// counter for hexadecimal
// number array
$i = 0;
while($n != 0)
{
// temporary variable
// to store remainder
$temp = 0;
// storing remainder
// in temp variable.
$temp = $n % 16;
// check if temp < 10
if($temp < 10)
{
$hexaDeciNum[$i] = chr($temp + 48);
$i++;
}
else
{
$hexaDeciNum[$i] = chr($temp + 55);
$i++;
}
$n = (int)($n / 16);
}
// printing hexadecimal number
// array in reverse order
for($j = $i - 1; $j >= 0; $j--)
echo $hexaDeciNum[$j];
}
// Driver Code
$n = 2545;
decToHexa($n);
// This code is contributed
// by mits.
?>
Time complexity: O(log16n)
Auxiliary space: O(1)
Using Predefined function
C++
// C++ program to convert decimal number to hexadecimal
#include <iostream>
using namespace std;
// function to convert decimal number to hexadecimal
void decToHexa(int n) { cout << hex << n << endl; }
// driver code
int main()
{
int n = 2545;
decToHexa(n);
return 0;
}
// This code is contributed by phasing17.
Java
// Java program to convert a decimal
// number to hexadecimal number
import java.io.*;
class GFG {
public static void decToHexa(int n)
{
System.out.println(Integer.toHexString(n));
}
public static void main(String[] args)
{
int n = 2545;
decToHexa(n);
}
}
Python
# function to convert decimal number
# to equivalent hexadecimal number
def decToHexa(n):
return hex(n).replace("0x", "")
# Driver Code
n = 2545
print(decToHexa(n))
C#
using System;
class GFG
{
public static void decToHexa(int n)
{
// Convert the decimal number to hexadecimal
Console.Write(Convert.ToString(n, 16));
}
public static void Main(String[] args)
{
int n = 2545;
decToHexa(n);
}
}
JavaScript
<script>
// JS program to convert a decimal
// number to hexadecimal number
// Function to convert decimal to hexadecimal base integer
function decToHexa(n)
{
document.write(n.toString(16));
}
// Driver Code
var n = 2545;
decToHexa(n);
// This code is contributed by phasing17
</script>
Time Complexity: O(log16(n)), because we divide the n by 16 till it becomes zero.
Auxiliary Space: O(1), we cannot use any extra space.
C++ Program to Convert Decimal to Hexadecimal
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem