Program to Convert Octal to Hexadecimal

• Difficulty Level : Basic
• Last Updated : 07 Dec, 2020

Given an Octal number, the task is to convert it into a Hexadecimal number.

Examples:

Input:  47
Output: 27
Explanation:
Decimal value of 47 is = (7 * 1) + (4 * 8) = 39

Now, convert this number to hexadecimal
39/16 -> quotient = 2, remainder = 7
2/16 ->  quotient = 0, remainder = 2

So, the equivalent hexadecimal number is = 27

Input: 235
Output:  9d

Approach:
An Octal Number or oct for short is the base-8 number and uses the digits 0 to 7. Octal numerals can be made from binary numerals by grouping consecutive binary digits into groups of three (starting from the right).

A Hexadecimal Number is a positional numeral system with a radix, or base, of 16 and uses sixteen distinct symbols. It may be a combination of alphabets and numbers. It uses numbers from 0 to 9 and alphabets A to F.

Steps of Conversion:
The simplest way is to convert the octal number into a decimal, then the decimal into hexadecimal form.

1. Write the powers of 8 (1, 8, 64, 512, 4096, and so on) beside the octal digits from bottom to top.
2. Multiply each digit by its power.
4. Divide the decimal number by 16.
5. Get the integer quotient for the next iteration (if the number will not divide equally by 16, then round down the result to the nearest whole number).
6. Keep a note of the remainder, it should be between 0 and 15.
7. Repeat the steps from step 4. until the quotient is equal to 0.
8. Write out all the remainders, from bottom to top.
9. Convert any remainders bigger than 9 into hex letters. This is the hex solution.

For example, if the given octal number is 5123:

Then the decimal number (2560 + 64 + 16 + 3) is: 2643

Finally, the hexadecimal number is: a53

Below is the implementation of the above approach:

Java

 // Java Program to Convert Octal// to Hexadecimal import java.util.Scanner; public class JavaProgram {    public static void main(String args[])    {        String octnum, hexnum;        int decnum;        Scanner scan = new Scanner(System.in);                 // Taking 5123 as an example of        // Octal Number.        octnum = "5123";                 // Convert Octal to Decimal        decnum = Integer.parseInt(octnum, 8);                 // Convert Decimal to Hexadecimal        hexnum = Integer.toHexString(decnum);         System.out.print("Equivalent Hexadecimal Value = "                                                + hexnum);    }}

Python3

 # Python3 program to convert octal# to hexadecimal # Taking 5123 as an example of# octal numberoctnum = "5123" # Convert octal to decimaldecnum = int(octnum, 8) # Convert decimal to hexadecimalhexadecimal = hex(decnum).replace("0x", "") # Printing the hexadecimal valueprint("Equivalent Hexadecimal Value =", hexadecimal) # This code is contributed by virusbuddah_