Given a decimal number as input, we need to write a program to convert the given decimal number into equivalent hexadecimal number. i.e convert the number with base value 10 to base value 16.
Hexadecimal numbers uses 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.
Input : 116 Output : 74 Input : 10 Output : A Input: 33 Output: 21
- Store the remainder when the number is divided by 16 in a temporary variable temp. If temp is less than 10, insert (48 + temp) in a character array otherwise if temp is greater than or equals 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.
If the given decimal number is 2545.
Step 1: Calculate remainder when 2545 is divided by 16 is 1. Therefore, temp = 1. As temp is less than 10. So, arr = 48 + 1 = 49 = ‘1’.
Step 2: Divide 2545 by 16. New number is 2545/16 = 159.
Step 3: Calculate remainder when 159 is divided by 16 is 15. Therefore, temp = 15. As temp is greater than 10. So, arr = 55 + 15 = 70 = ‘F’.
Step 4: Divide 159 by 16. New number is 159/16 = 9.
Step 5: Calculate remainder when 9 is divided by 16 is 9. Therefore, temp = 9. As temp is less than 10. So, arr = 48 + 9 = 57 = ‘9’.
Step 6: Divide 9 by 16. New number is 9/16 = 0.
Step 7: Since number becomes = 0. Stop repeating steps and print the array in reverse order. Therefore the equivalent hexadecimal number is 9F1.
Below diagram shows an example of converting the decimal number 2545 to equivalent hexadecimal number.
Below is the implementation of above idea.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check input character is alphabet, digit or special character
- Numbers with exactly 3 divisors
- Number of substrings divisible by 4 in a string of integers
- Program for Decimal to Binary Conversion
- Program for Binary To Decimal Conversion
- Divide large number represented as string
- Convert a binary number to hexadecimal number
- Converting a Real Number (between 0 and 1) to Binary String
- GCD of more than two (or array) numbers
- Constructors in Java
- Find the maximum number of handshakes
- Convert from any base to decimal and vice versa
- Program to find LCM of two numbers
- Program for Fibonacci numbers
- Write an Efficient C Program to Reverse Bits of a Number