RUN


Program to convert hexadecimal to octal

What Are Hexadecimal Numbers?

Hexadecimal numbers are the numbers having base 16. It uses 16 different digits to represent the numbers. It may be a combination of alphabets and numbers. It uses numbers from 0 to 9 and alphabets A to F.

Example: (5D2)16, (9AD1)16, (ABC)16

What are Octal Numbers?

Octal numbers are numbers having base 8. These numbers use digits 0 to 7. It is denoted as o8 and o is an octal decimal number.

Example: (11)8, (321)8,(46)8

# Hexadecimal to Octal Conversion (Algorithm)

Conversion of hexadecimal to octal cannot be done directly. Firstly we need to convert hexadecimal into its equivalent decimal number then decimal to octal. Follow the steps below to understand the process.

  1. Consider the given hexadecimal number and count the number of digits in the number.
  2. If n is the position of the digit from the right end then multiply each digit with 16n-1
  3. Add the terms after multiplication. Resultant is the equivalent decimal form
  4. Divide the decimal number with 8. Note down the remainder.
  5. Continue step 6 and 7 with the quotient, until the quotient is zero
  6. Write the remainders in reverse order
  7. The obtained number is the required result.

Example:

Input:- Hexadecimal number: 5D6C

Output:- Octal number: 56554

Code:

// C Program for Hexadecimal to Octal Conversion

#include<stdio.h>

#include<string.h>

#include<math.h>

int convert(char hexa[])

{

    int i,size, deci=0, octa=0;

    for(size=0; hexa[size]!='\0'; size++);  //this loop calculates size of hexadecimal number

    for(i=0; hexa[i]!='\0'; i++,size--)

    {

        if(hexa[i]>='0' && hexa[i]<='9')

        { 

            deci= deci + (hexa[i]-'0')*pow(16,size-1);

        }

        if(hexa[i]>='A' && hexa[i]<='F')

        {

            deci = deci + (hexa[i]-55)*pow(16,size-1);

        }

        if(hexa[i]>='a' && hexa[i]<='f')

        {

            deci = deci + (hexa[i]-87)*pow(16,size-1);

        }

    } // deci contains the decimal value of given hexadecimal number. 

    i=1;

    while(deci!=0)

    {

        octa = octa + (deci%8)*i;

        deci = deci/8;

        i = i*10;

    }

    return octa;

}

int main()

{

    char hexa[20];

    printf("Enter Hexadecimal Number : ");

    scanf("%s",hexa);

    printf("Equivalent Octal Value = %d",convert(hexa));

    return 0;

}

Report Error/ Suggestion

Related Posts:

[yuzo_views]



Interview Questions



CopyRight © 2020

CopyRight © 2020