Open In App

Program to Convert Octal to Hexadecimal

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.
  3. Add up the answers. This is the decimal solution.
  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:

Digit Power Multiplication
5 512 2560
1 64 64
2 8 16
3 1 3

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

Division Quotient Remainder
2643/16 165 3
165/16 10 5
10/16 0 10 (a)

Finally, the hexadecimal number is: a53

Below is the implementation of the above approach: 

C++




// C++ program to convert Octal
// to Hexadecimal
#include<bits/stdc++.h>
using namespace std;
 
// Function to convert octal to decimal
int octalToDecimal(int n)
{
    int num = n;
    int dec_value = 0;
     
    // Initializing base value
    // to 1, i.e 8^0
    int base = 1;
   
    int temp = num;
    while (temp)
    {
         
        // Extracting last digit
        int last_digit = temp % 10;
        temp = temp / 10;
         
        // Multiplying last digit with
        // appropriate base value and
        // adding it to dec_value
        dec_value += last_digit * base;
   
        base = base * 8;
    }
    return dec_value;
}
 
// Function to convert decimal
// to hexadecimal
string decToHexa(int n)
{
     
    // char array to store
    // hexadecimal number
    char hexaDeciNum[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] = temp + 48;
            i++;
        }
        else
        {
            hexaDeciNum[i] = temp + 87;
            i++;
        }
        n = n / 16;
    }
     
    string ans = "";
       
    // Printing hexadecimal number array
    // in reverse order
    for(int j = i - 1; j >= 0; j--)
    {
        ans += hexaDeciNum[j];
    }
    return ans;
}
 
// Driver Code
int main()
{
    string hexnum;
    int decnum, octnum;
     
    // Taking 5123 as an example of
    // Octal Number.
    octnum = 5123;
     
    // Convert Octal to Decimal
    decnum = octalToDecimal(octnum);
     
    // Convert Decimal to Hexadecimal
    hexnum = decToHexa(decnum);
     
    cout << "Equivalent Hexadecimal Value = "
         << hexnum << endl;
}
 
// This code is contributed by pratham76


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 number
octnum = "5123"
 
# Convert octal to decimal
decnum = int(octnum, 8)
 
# Convert decimal to hexadecimal
hexadecimal = hex(decnum).replace("0x", "")
 
# Printing the hexadecimal value
print("Equivalent Hexadecimal Value =", hexadecimal)
 
# This code is contributed by virusbuddah_


C#




// C# Program to Convert Octal
// to Hexadecimal
using System;
class GFG{
     
// Function to convert octal
// to decimal
static int octalToDecimal(int n)
{
  int num = n;
  int dec_value = 0;
 
  // Initializing base value 
  // to 1, i.e 8^0
  int b_ase = 1;
 
  int temp = num;
  while (temp > 0) 
  {
    // Extracting last digit
    int last_digit = temp % 10;
    temp = temp / 10;
 
    // Multiplying last digit 
    // with appropriate base 
    // value and adding it to 
    // dec_value
    dec_value += last_digit * b_ase;
 
    b_ase = b_ase * 8;
  }
   
  return dec_value;
}
 
// Function to convert decimal
// to hexadecimal
static string decToHexa(int n)
  // char array to store 
  // hexadecimal number
  char []hexaDeciNum = new char[100];
 
  // counter for hexadecimal
  // number array
  int i = 0;
  string ans = "";
 
  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 + 87);
      i++;
    }
 
    n = n / 16;
  }
 
  for(int j = i - 1; j >= 0; j--)
  {
    ans += hexaDeciNum[j];
  }
   
  return ans;
}
   
// Driver code
public static void Main(string []args)
{
  string octnum, hexnum;
  int decnum;
 
  // Taking 5123 as an
  // example of Octal Number.
  octnum = "5123";
 
  // Convert Octal to Decimal
  decnum = octalToDecimal(Int32.Parse(octnum));
 
  // Convert Decimal to Hexadecimal
  hexnum = decToHexa(decnum);
 
  Console.Write("Equivalent Hexadecimal Value = " +
                 hexnum);
}
}
 
// This code is contributed by rutvik_56


Javascript




// JavaScript program to convert Octal
// to Hexadecimal
 
 
// Function to convert octal to decimal
function octalToDecimal( n)
{
    var num = n;
    var dec_value = 0;
     
    // Initializing base value
    // to 1, i.e 8^0
    var base = 1;
   
    var temp = num;
    while (temp > 0)
    {
        // Extracting last digit
        var last_digit = temp % 10;
        temp = Math.floor(temp / 10);
         
        // Multiplying last digit with
        // appropriate base value and
        // adding it to dec_value
        dec_value += last_digit * base;
   
        base = base * 8;
    }
    return dec_value;
}
 
// Function to convert decimal
// to hexadecimal
function decToHexa( n)
{
     
    // char array to store
    // hexadecimal number
    var hexaDeciNum = new Array(100);
     
    // 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] = temp + 48;
            i++;
        }
        else
        {
            hexaDeciNum[i] = temp + 87;
            i++;
        }
        n = Math.floor(n / 16);
    }
     
    var ans = "";
       
    // Printing hexadecimal number array
    // in reverse order
    for(var j = i - 1; j >= 0; j--)
    {
        ans += String.fromCharCode(hexaDeciNum[j]);
    }
    return ans;
}
 
// Driver Code
var hexnum;
var decnum, octnum;
     
// Taking 5123 as an example of
// Octal Number.
octnum = 5123;
     
// Convert Octal to Decimal
decnum = octalToDecimal(octnum);
     
// Convert Decimal to Hexadecimal
hexnum = decToHexa(decnum);
 
console.log("Equivalent Hexadecimal Value = " + hexnum);
 
 
// This code is contributed by phasing17


Output

Equivalent Hexadecimal Value = a53







Time Complexity: O(logN),The time complexity of this algorithm is O(logN), where N is the octal number. This is because we use a loop which iterates through the octal number and performs some operations on each iteration.
Space Complexity: O(N),The space complexity of this algorithm is O(N), where N is the octal number. This is because we use an array to store the hexadecimal number and this array can have up to N elements.

Optimized Approach:

There are a few minor improvements that can be made:

  • Avoid using char array to store hexadecimal digits: Instead of using a character array to store the hexadecimal digits, we can directly concatenate the hexadecimal digits to a string. This would make the code simpler and avoid the need for reversing the character array.
  • Combine octal to decimal and decimal to hexadecimal conversion functions: Since we need to convert octal to decimal and then decimal to hexadecimal, we can combine these two functions into a single function to avoid unnecessary function calls and variable assignments.

Here’s the optimized code:

C++




#include <iostream>
using namespace std;
 
// Function to convert octal to hexadecimal
string octalToHexadecimal(int n)
{
    int decimal = 0, base = 1;
    while (n > 0) {
        int rem = n % 10;
        decimal += rem * base;
        n /= 10;
        base *= 8;
    }
     
    string hexadecimal = "";
    while (decimal > 0) {
        int rem = decimal % 16;
        if (rem < 10) {
            hexadecimal = to_string(rem) + hexadecimal;
        } else {
            hexadecimal = (char)(rem - 10 + 'A') + hexadecimal;
        }
        decimal /= 16;
    }
    return hexadecimal;
}
 
// Driver code
int main()
{
    int octal = 5123;
    string hexadecimal = octalToHexadecimal(octal);
    cout << "Equivalent Hexadecimal Value = " << hexadecimal << endl;
    return 0;
}


Java




import java.util.*;
 
public class Main {
    // Function to convert octal to decimal
    public static int octalToDecimal(int n) {
        int num = n;
        int dec_value = 0;
 
        // Initializing base value to 1, i.e 8^0
        int base = 1;
 
        int temp = num;
        while (temp != 0) {
            // Extracting last digit
            int last_digit = temp % 10;
            temp /= 10;
 
            // Multiplying last digit with appropriate base value and adding it to dec_value
            dec_value += last_digit * base;
 
            base *= 8;
        }
        return dec_value;
    }
 
    // Function to convert decimal to hexadecimal
    public static String 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 /= 16;
        }
 
        String ans = "";
 
        // Printing hexadecimal number array in reverse order
        for (int j = i - 1; j >= 0; j--) {
            ans += hexaDeciNum[j];
        }
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args) {
        int octnum = 5123;
 
        // Convert Octal to Decimal
        int decnum = octalToDecimal(octnum);
 
        // Convert Decimal to Hexadecimal
        String hexnum = decToHexa(decnum);
 
        System.out.println("Equivalent Hexadecimal Value = " + hexnum);
    }
}


Python3




def octalToDecimal(n):
    num = n
    dec_value = 0
    base = 1
    temp = num
    while temp:
        last_digit = temp % 10
        temp = temp // 10
        dec_value += last_digit * base
        base = base * 8
    return dec_value
 
def decToHexa(n):
    hexaDeciNum = ''
    while n != 0:
        temp = 0
        temp = n % 16
        if temp < 10:
            hexaDeciNum = str(temp) + hexaDeciNum
        else:
            hexaDeciNum = chr(temp + 87) + hexaDeciNum
        n = n // 16
    return hexaDeciNum
 
# Driver code
if __name__ == '__main__':
    octnum = 5123
    decnum = octalToDecimal(octnum)
    hexnum = decToHexa(decnum)
    print("Equivalent Hexadecimal Value = {}".format(hexnum))


C#




using System;
 
namespace OctalToHexadecimal
{
    class Program
    {
        // Function to convert octal to decimal
        static int OctalToDecimal(int n)
        {
            int num = n;
            int dec_value = 0;
            int base_value = 1;
 
            while (num != 0)
            {
                int last_digit = num % 10;
                num = num / 10;
                dec_value += last_digit * base_value;
                base_value = base_value * 8;
            }
 
            return dec_value;
        }
 
        // Function to convert decimal to hexadecimal
        static string DecimalToHexadecimal(int n)
        {
            char[] hexaDeciNum = new char[100];
            int i = 0;
 
            while (n != 0)
            {
                int temp = 0;
                temp = n % 16;
 
                if (temp < 10)
                {
                    hexaDeciNum[i] = (char)(temp + 48);
                    i++;
                }
                else
                {
                    hexaDeciNum[i] = (char)(temp + 55);
                    i++;
                }
                n = n / 16;
            }
 
            string hexadecimal = new string(hexaDeciNum, 0, i);
            return hexadecimal;
        }
 
        // Main function
        static void Main(string[] args)
        {
            int octalNum = 5123;
            int decimalNum = OctalToDecimal(octalNum);
            string hexadecimalNum = DecimalToHexadecimal(decimalNum);
 
            Console.WriteLine("Equivalent Hexadecimal Value = " + hexadecimalNum);
        }
    }
}


Javascript




// Function to convert octal to decimal
function octalToDecimal(n) {
  let num = n;
  let dec_value = 0;
  let base = 1;
 
  let temp = num;
  while (temp) {
    let last_digit = temp % 10;
    temp = Math.floor(temp / 10);
    dec_value += last_digit * base;
    base *= 8;
  }
  return dec_value;
}
 
// Function to convert decimal to hexadecimal
function decToHexa(n) {
  let hexaDeciNum = [];
  let i = 0;
  while (n != 0) {
    let temp = 0;
    temp = n % 16;
    if (temp < 10) {
      hexaDeciNum[i] = temp + 48;
    } else {
      hexaDeciNum[i] = temp + 87;
    }
    i++;
    n = Math.floor(n / 16);
  }
  let ans = "";
  for (let j = i - 1; j >= 0; j--) {
    ans += String.fromCharCode(hexaDeciNum[j]);
  }
  return ans;
}
 
// Driver code
let octnum = 5123;
let decnum = octalToDecimal(octnum);
let hexnum = decToHexa(decnum);
console.log("Equivalent Hexadecimal Value = " + hexnum);


Output

Equivalent Hexadecimal Value = A53







Time Complexity: O(logN)
Auxiliary Space: O(N)

Method: Using Look-up table method

First, an unordered map is created to store the hexadecimal values for each possible remainder when dividing a decimal number by 16. The octal input number is then converted to its decimal representation using the usual method of multiplying each digit by its corresponding power of 8 and summing the results. Finally, the decimal number is converted to its hexadecimal representation by repeatedly dividing by 16 and looking up the corresponding hexadecimal digit from the lookup table.

C++




#include <iostream>
#include <string>
#include <unordered_map>
 
using namespace std;
 
// Function to convert octal to hexadecimal
string octalToHexadecimal(int n)
{
    // Lookup table for hexadecimal values
    unordered_map<int, char> hexLookupTable{
        {0, '0'}, {1, '1'}, {2, '2'}, {3, '3'},
        {4, '4'}, {5, '5'}, {6, '6'}, {7, '7'},
        {8, '8'}, {9, '9'}, {10, 'A'}, {11, 'B'},
        {12, 'C'}, {13, 'D'}, {14, 'E'}, {15, 'F'}
    };
 
    // Convert octal to decimal
    int decimal = 0, base = 1;
    while (n > 0) {
        int rem = n % 10;
        decimal += rem * base;
        n /= 10;
        base *= 8;
    }
 
    // Convert decimal to hexadecimal
    string hexadecimal = "";
    while (decimal > 0) {
        int rem = decimal % 16;
        hexadecimal = hexLookupTable[rem] + hexadecimal;
        decimal /= 16;
    }
    return hexadecimal;
}
 
// Driver code
int main()
{
    int octal = 5123;
    string hexadecimal = octalToHexadecimal(octal);
    cout << "Equivalent Hexadecimal Value = " << hexadecimal << endl;
    return 0;
}


Java




import java.util.HashMap;
 
public class GFG {
 
    // Function to convert octal to hexadecimal
    public static String octalToHexadecimal(int n) {
        // Lookup table for hexadecimal values
        HashMap<Integer, Character> hexLookupTable = new HashMap<>();
        hexLookupTable.put(0, '0');
        hexLookupTable.put(1, '1');
        hexLookupTable.put(2, '2');
        hexLookupTable.put(3, '3');
        hexLookupTable.put(4, '4');
        hexLookupTable.put(5, '5');
        hexLookupTable.put(6, '6');
        hexLookupTable.put(7, '7');
        hexLookupTable.put(8, '8');
        hexLookupTable.put(9, '9');
        hexLookupTable.put(10, 'A');
        hexLookupTable.put(11, 'B');
        hexLookupTable.put(12, 'C');
        hexLookupTable.put(13, 'D');
        hexLookupTable.put(14, 'E');
        hexLookupTable.put(15, 'F');
 
        // Convert octal to decimal
        int decimal = 0, base = 1;
        while (n > 0) {
            int rem = n % 10;
            decimal += rem * base;
            n /= 10;
            base *= 8;
        }
 
        // Convert decimal to hexadecimal
        StringBuilder hexadecimal = new StringBuilder();
        while (decimal > 0) {
            int rem = decimal % 16;
            hexadecimal.insert(0, hexLookupTable.get(rem));
            decimal /= 16;
        }
        return hexadecimal.toString();
    }
 
    // Driver code
    public static void main(String[] args) {
        int octal = 5123;
        String hexadecimal = octalToHexadecimal(octal);
        System.out.println("Equivalent Hexadecimal Value = " + hexadecimal);
    }
}


Python3




def octal_to_hexadecimal(n):
    # Lookup table for hexadecimal values
    hex_lookup_table = {
        0: '0', 1: '1', 2: '2', 3: '3',
        4: '4', 5: '5', 6: '6', 7: '7',
        8: '8', 9: '9', 10: 'A', 11: 'B',
        12: 'C', 13: 'D', 14: 'E', 15: 'F'
    }
 
    # Convert octal to decimal
    decimal = 0
    base = 1
    while n > 0:
        rem = n % 10
        decimal += rem * base
        n //= 10
        base *= 8
 
    # Convert decimal to hexadecimal
    hexadecimal = ""
    while decimal > 0:
        rem = decimal % 16
        hexadecimal = hex_lookup_table[rem] + hexadecimal
        decimal //= 16
    return hexadecimal
 
# Driver code
octal = 5123
hexadecimal = octal_to_hexadecimal(octal)
print("Equivalent Hexadecimal Value =", hexadecimal)


C#




using System;
using System.Collections.Generic;
 
public class GFG
{
    // Function to convert octal to hexadecimal
    public static string OctalToHexadecimal(int n)
    {
        // Lookup table for hexadecimal values
        Dictionary<int, char> hexLookupTable = new Dictionary<int, char>()
        {
            {0, '0'}, {1, '1'}, {2, '2'}, {3, '3'},
            {4, '4'}, {5, '5'}, {6, '6'}, {7, '7'},
            {8, '8'}, {9, '9'}, {10, 'A'}, {11, 'B'},
            {12, 'C'}, {13, 'D'}, {14, 'E'}, {15, 'F'}
        };
 
        // Convert octal to decimal
        int decimalNum = 0, baseVal = 1;
        while (n > 0)
        {
            int rem = n % 10;
            decimalNum += rem * baseVal;
            n /= 10;
            baseVal *= 8;
        }
 
        // Convert decimal to hexadecimal
        string hexadecimal = "";
        while (decimalNum > 0)
        {
            int rem = decimalNum % 16;
            hexadecimal = hexLookupTable[rem] + hexadecimal;
            decimalNum /= 16;
        }
        return hexadecimal;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int octal = 5123;
        string hexadecimal = OctalToHexadecimal(octal);
        Console.WriteLine("Equivalent Hexadecimal Value = " + hexadecimal);
    }
}


Javascript




function OctalToHexadecimal(n) {
    // Lookup table for hexadecimal values
    const hexLookupTable = {
        0: '0', 1: '1', 2: '2', 3: '3',
        4: '4', 5: '5', 6: '6', 7: '7',
        8: '8', 9: '9', 10: 'A', 11: 'B',
        12: 'C', 13: 'D', 14: 'E', 15: 'F'
    };
 
    // Convert octal to decimal
    let decimalNum = 0;
    let baseVal = 1;
    while (n > 0) {
        let rem = n % 10;
        decimalNum += rem * baseVal;
        n = Math.floor(n / 10);
        baseVal *= 8;
    }
 
    // Convert decimal to hexadecimal
    let hexadecimal = "";
    while (decimalNum > 0) {
        let rem = decimalNum % 16;
        hexadecimal = hexLookupTable[rem] + hexadecimal;
        decimalNum = Math.floor(decimalNum / 16);
    }
    return hexadecimal;
}
 
// Driver code
const octal = 5123;
const hexadecimal = OctalToHexadecimal(octal);
console.log("Equivalent Hexadecimal Value = " + hexadecimal);


Output

Equivalent Hexadecimal Value = A53








The time complexity of the code is O(log n) since it involves converting the octal number to decimal and then to hexadecimal, both of which have a logarithmic time complexity.

The auxiliary space complexity is O(n) since only a small unordered map is created, which does not depend on the size of the input.



Last Updated : 19 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads