C Program to Convert Octal to Hexadecimal

In this tutorial, we will write a program to convert octal to hexadecimal in C. Before that, you must have knowledge of the following topics in C.

  • C operator
  • C while loop
  • C for loop

Hexadecimal number

The hexadecimal number is represented with a base of 16. It has digits from 0 to 15 to represent, However after 9 the values are represented in Alphabet till 15 such as 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E, and 15 as F.

Octal number

The octal numbers are the numbers with base 8 and use the digits 0 to 7. Example: 8 in decimal is represented as 10 in octal, 25 as 31, and so on.

Let us go through a program for the Octal to Hexadecimal Conversion in C.


C Program to Convert Octal to Hexadecimal

#include <stdio.h>
#include <math.h>

int main()
{
  int octalNum, rem, i = 0;
  char HexaDecimal[100];
  int decimalNum = 0, sem = 0;

  printf("Enter an Octal number: ");
  scanf("%d", &octalNum);

  //Octal to decimal covert
  while (octalNum != 0)
  {
    decimalNum = decimalNum + (octalNum % 10) *pow(8, sem);
    sem++;
    octalNum /= 10;
  }

  //Decimal to Hexadecimal
  while (decimalNum != 0)
  {
    rem = decimalNum % 16;

    if (rem < 10)
      HexaDecimal[i++] = rem + 48; // 48 Ascii=0
    else
      HexaDecimal[i++] = rem + 55; //55 Ascii=7

    decimalNum /= 16;
  }

  printf("Equivalent Hexadecimal Value: ");
  int j;

  for (j = i - 1; j >= 0; j--)
    printf("%c", HexaDecimal[j]);

  return 0;
}

Output:

Enter an Octal number: 377
Equivalent Hexadecimal Value: FF