C++ Program to Convert Hexadecimal to Octal

« Previous Program Next Program »

Hexadecimal to Octal Conversion in C++

To convert hexadecimal number to octal number in C++ programming, you have to ask to the user to enter the hexadecimal number to convert it into octal number to display the equivalent value in octal format as shown here in the following program.

C++ Programming Code to Convert Hexadecimal to Octal

Following C++ program ask to the user to enter any number in Hexadecimal format to convert it into octal, then display the result on the screen:

Here first we will convert the entered hexadecimal number into decimal number then we will convert it into octal number. That is, from hexadecimal to octal.

/* C++ Program - Hexadecimal to Octal Conversion */
int hex_to_oct(char hex[]);
void main()
	char hex[20],c;
	int n;
	cout<<"Enter Hexadecimal Number : ";
	cout<<"Equivalent Octal Value = %d",hex_to_oct(hex);
int hex_to_oct(char hex[])
	int i,len, dec=0, oct=0;
	for(len=0; hex[len]!='\0'; len++);
	for(i=0; hex[i]!='\0'; i++,len--)
		if(hex[i]>='0' && hex[i]<='9')
			dec= dec + (hex[i]-'0')*pow(16,len-1);
		if(hex[i]>='A' && hex[i]<='F')
			dec = dec + (hex[i]-55)*pow(16,len-1);
		if(hex[i]>='a' && hex[i]<='f')
			dec = dec + (hex[i]-87)*pow(16,len-1);
	} /* Now dec contains the decimal value of given hexadecimal number. */
		oct = oct + (dec%8)*i;
		dec = dec/8;
		i = i*10;
	return oct;

When the above C++ program is compile and executed, it will produce the following result:

C++ program convert hexadecimal to octal

Same Program in Other Language

You may like the same program in other programming languages:

« Previous Program Next Program »


Quick Links
Signup - Login - Give Online Test