Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Problem Statement
1.2.
Sample Example
2.
Naive Approach
2.1.
Implementation in C++
2.2.
Complexity Analysis
3.
Using Predefined function
3.1.
Implementation in C++
3.2.
Complexity Analysis
4.
Frequently Asked Questions
4.1.
What are the Common Types of Number System?
4.2.
Why do we use hexadecimal?
4.3.
How do Hexadecimals work?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

decimal to hexadecimal in C++

Author Ayush Tiwari
3 upvotes

Introduction

There are mathematical calculations that must occasionally be made in programming, and conversion from decimal to hexadecimal in C++ simple and straightforward.

Let's first discuss decimal and hexadecimal numbers.

Decimal Number:  The most widely used and accepted system in daily life is the decimal numeral system. It bases itself on the number 10. (radix). Consequently, it has ten symbols: The digits 0 through 9, specifically 0, 1, 2, 3, 4, 5, 6, 7, and 9.

Many ancient civilizations used the decimal numeral system, which is one of the earliest numeral systems that is currently known. The Hindu-Arabic numeral system solved the problem of representing very large numbers in the decimal system. Using powers of base 10, the Hindu-Arabic numeral system assigns positions to each digit in a number. Each digit is then raised to the nth power according to its position.

Hexadecimal Number: The base of the hexadecimal system (abbreviated hex) is 16. (radix). It uses 16 symbols because it is a base-16 numeral system. The first six letters of the English alphabet are A, B, C, D, E, and F, and the first ten decimal digits are 0 through 9 (0, 1, 2, 3, 5, 6, 7, and 8). The need to represent the numbers 10, 11, 12, 13, 14, and 15 in a single symbol necessitates the use of the letters.

In mathematics and information technology, hex is used to represent binary numbers because it is more aesthetically pleasing. Hex is a language used to write binary in an abbreviated form because each hex digit represents four binary digits.

A half-byte (also known as a nibble) is made up of four binary digits. Accordingly, a single byte can store binary values between 0000 0000 and 1111 1111. These can be more amiably represented in hex, where they range from 00 to FF.

In HTML programming, colours are denoted by a 6-digit hexadecimal number. For example, white is denoted by FFFFFF, while black is denoted by 000000.

We use following table to covert decimal to hexadecimal in c++.

          Hexadecimal Digit                   Decimal Digit
                    0                     0
                    1                     1
                    2                     2
                    3                     3
                    4                     4
                    5                     5
                    6                     6
                    7                     7
                    8                     8
                    9                     9
                    A                     10
                    B                     11
                    C                     12
                    D                     13
                    E                     14
                    F                     15

Problem Statement

Write a program to convert decimal to hexadecimal in c++. i.e. convert a given decimal number into an equivalent hexadecimal number from input of a decimal number is given.

Sample Example

Input 1: 

Decimal number = 5386

 

Output 1:

Heaxadecimal = 150A

 

Input 2:

Decimal number = 2545

 

Output 2:

Hexadecimal = 9F1

Also Read - C++ Interview Questions and Application of Oops

Naive Approach

This method, which involves dividing the number to be converted, is simple. Since the hexadecimal number system's base number is 16, if N is a decimal number, divide it by 16. Write down the remainder's value, which will range from 0 to 15. (replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Divide the final decimal number once more until it equals 0, and record the results of each division. The remainders, which are equivalent hexadecimal numbers to the given decimal number, should then be written from bottom to top (or in reverse order).

The following procedures must be used to perform some fundamental mathematical calculations in order to convert decimal to hexadecimal in c++: 

Step 1: First, divide the value in the given decimal number system by 16, then note the result.

Step 2: Divide the quotient by 16 in step two. Continue doing this until the quotient is equal to zero.

Step 3: Replace the numbers 10, 11, 12, 13, 14, and 15 in the remainders, respectively, with the letters A, B, C, D, E, and F.

Step 4: Arrange all of the values of the remainder using the reverse order pattern.

The obtained number is the necessary hexadecimal number, 

The formula for converting the given numbers from decimal to hexadecimal is,

P10 = Q16

a decimal number P and a hexadecimal number Q are present.

With the aid of the following example, let's learn how to change a decimal number into a hexadecimal number.

An example would be to hexadecimal the number 5386.

Example of 5386 conversion

Implementation in C++

// converting decimal to hexadecimal in c++
#include <bits/stdc++.h>
using namespace std;
// function to convert decimal to hexadecimal in c++
string convertHexa(int number)
{
    string hexa;
    // loop till number>0
    while (number)
    {
        int rem = number % 16;
        // when rem is less than 10 then store 0-9
        // else store A - F
        if (rem < 10)
            hexa.push_back(rem + '0');
        else
            hexa.push_back(rem - 10 + 'A');

        number = number / 16;
    }
    reverse(hexa.begin(), hexa.end());
    return hexa;
}
// drive code
int main()
{
    int number; // store decimal number
    cin >> number;

    string hexa; // store hexadecimal
    // calling function to convert decimal to hexadecimal in c++
    hexa = convertHexa(number);
    // printing hexadecimal;
    cout << hexa << endl;
}
You can also try this code with Online C++ Compiler
Run Code

 

Input: 

7654
You can also try this code with Online C++ Compiler
Run Code

 

Output: 

1DE6
You can also try this code with Online C++ Compiler
Run Code

 

Try and compile by yourself with the help of online C++ Compiler for better understanding.

Complexity Analysis

Time Complexity: O(log16(number)), because we divide the number by 16 till it becomes zero.

Space Complexity: O(1), we cannot use any extra space.

Using Predefined function

We can also use the predefined function to convert decimal to hexadecimal in c++,  The implementation in std is the same as the above approach:

Syntax:

cout << hex << n << endl;
You can also try this code with Online C++ Compiler
Run Code

 

Here, n is the decimal number.

Implementation in C++

// converting decimal to hexadecimal in c++
#include <bits/stdc++.h>
using namespace std;
// function to convert decimal to hexadecimal in c++
void convertHexa(int number)
{
    cout << hex << number << endl;
}
// drive code
int main()
{
    int number; // store decimal number
    cin >> number;
    // calling function to convert decimal to hexadecimal in c++
    convertHexa(number);
}
You can also try this code with Online C++ Compiler
Run Code

 

Input: 

9483
You can also try this code with Online C++ Compiler
Run Code

Output: 

250B
You can also try this code with Online C++ Compiler
Run Code

Complexity Analysis

Time and space complexity is the same as the iterative method.

Time Complexity: O(log16(number)), because we divide the number by 16 till it becomes zero.

Space Complexity: O(1), we cannot use any extra space.

Must read decimal to binary c++ 

Frequently Asked Questions

What are the Common Types of Number System?

The four most common number system types are:

  • Decimal number system (Base- 10)
  • Binary number system (Base- 2)
  • Octal number system (Base-8)
  • Hexadecimal number system (Base- 16)

Why do we use hexadecimal?

Hexadecimal numbers are frequently used by software developers and system designers because they offer a human-friendly representation of binary-coded values. Four bits (binary digits), also referred to as a nibble, are represented by each hexadecimal digit (or nybble). An 8-bit byte, for instance, can have values in binary form that range from 00000000 to 11111111, which is conveniently represented as 00 to FF in hexadecimal.

How do Hexadecimals work?

The base-16 numbering system used in hexadecimal is. With fewer digits, it can be used to represent large numbers. This system consists of six alphabetic characters, A, B, C, D, E, and F, followed by 16 symbols, or possible digit values from 0 to 9.

Conclusion

I hope this article provided you with how to convert decimal to hexadecimal in c++; we use two methods Iterative and using predefined to convert decimal to hexadecimal in c++.

Also check out this article - Pair in C++

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem DesignMachine learning, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!!

Live masterclass