Hello all. I'm writing a program that converts from any cominbation of base 2, 8, 10, and 16. So far I have this code and I want to convert from hexadecimal to octal but it doesn't work. I would appreciate any help. Thank you!

Here is the code:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <bitset>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <limits>
#include <sstream>
#include <bitset>



#define ULONG unsigned long
#define FALSE 0
#define TRUE 1
#define BOOL int
#define MAX 1000



using namespace std;


void B2D();
void B2O();
void B2H();
void D2B();
void D2OH();
void O2D();
void O2H();
void H2D();
void H2O();
void H2B();

void binary(int);

 int Binaryy;


BOOL oct2dec(ULONG oct, ULONG *dec) {
ULONG digit, result=0, place=1;
while(oct!=0) {
digit = oct % 10;
if(digit>7) { return FALSE; }
oct = oct/10;
result += digit * place;
place *= 8;
}
*dec = result;
return TRUE;
}

void dec2hex(ULONG dec) {
ULONG digit = dec % 16;
if(dec>15) {  dec2hex(dec/16); }
printf("%c", (digit>9) ? digit - 10 + 'A' : '0' + digit );
}

void processEntry(ULONG octalValue) {
ULONG decimalValue;
//printf("Value is %ld\n", octalValue);
if (!oct2dec(octalValue, &decimalValue)) {
printf("Sorry out of range..\n");
return;
}
//printf("Decimal Value is %ld\n", decimalValue);
printf("Hexadecimal eq= ");
dec2hex(decimalValue);
printf("\n");
}




int main()
{

    char MenuChoice = '1';
    while(MenuChoice != '0')
    {

cout << "a. Binary to Decimal"<< endl;
cout << "b. Binary to Octal"<< endl;
cout << "c. Binary to Hexadecimal"<< endl;
cout << "d. Decimal to Binary"<< endl;
cout << "e. Decimal to Octal and Hexadecimal"<< endl;
cout << "f. Octal to Decimal"<< endl;
cout << "g. Octal to Hexadecimal"<< endl;
cout << "h. Hexadecimal to Decimal"<< endl;
cout << "i. Hexadecimal to Octal"<< endl;
cout << "j. Hexadecimal to Binary"<< endl;

        cout << "0. Quit" << endl;
        cout << "Menu Choice: ";

        cin >> MenuChoice;
        cout << endl;

        switch (MenuChoice)
        {
        case 'a':
            B2D();
            break;

        case 'b':
            B2O();
            break;

case 'c':
B2H();
break;

case 'd':
D2B();
break;

case 'e':
D2OH();
break;

case 'f':
O2D();
break;

case 'g':
O2H();
break;

case 'h':
H2D();
break;

case 'i':
H2O();
break;

case 'j':
H2B();
break;


        case '0':
            break;

        default:
            cout << "Choose only 0-4 please"<< endl;
        }
    }
    return 0;
}

void B2D()
{
 cout<< "Binary: ";   cin>>Binaryy;


 int Digit[11]; 
 int k = 1, i = 0;
 while (Binaryy/k != 0)
 {
  Digit[i] = (Binaryy/k) % 10;
  i++;
  k *= 10; //k = k*10;
 }

 int Decimal = 0; i = 0;
 while (Digit[i] != -858993460) 
 {
  Decimal += Digit[i]*pow(2,i); 
  i++;
 }
 cout<< "Decimal: "<<Decimal<<endl;
}




void B2O()
{
char num_str[50];

cout << "\n Enter the binary value you wish to convert into octal: ";
cin  >> num_str;

long num_l = strtol(num_str, NULL, 2); 
_ltoa_s (num_l, num_str, 8); 
cout << "\n The octal representation of the given binary is: " << num_str << "\n\n";
}
void D2B()
{
int number;

cout << "\n Enter the decimal value you wish to convert into binary: ";
cin >> number;
if (number < 0) 
cout << "That is not a positive integer.\n";
else {
cout << number << "\n The binary representation of the given decimal is: ";
binary(number);
cout << endl;
}
}

void binary(int number) {
int remainder;

if(number <= 1) {
cout << number;
return;
}

remainder = number%2;
binary(number >> 1);    
cout << remainder;
}

void B2H()
{
long int longint=0;
string buf;
cout<<"\n Enter the binary value you wish to convert into hexadecimal: "<<endl;
cin>>buf;
int len=buf.size();
for(int i=0;i<len;i++)
{
longint+=( buf[len-i-1]-48) * pow(2,i);


}
cout<<setbase(16);
cout<<"\n The hexadecimal representation of the given binary is:";
cout<<longint<<endl<<endl;
}

void D2OH()
{
     int n;
    cout << "\n Enter the decimal value you wish to convert into octal and hexadecimal: ";
    cin >> n;
    cin.ignore( numeric_limits<streamsize>::max(), '\n' );

    cout << "\n The hexadecimal representation of the given decimal is:" << hex << n << endl;

    cout << "\n The octal representation of the given decimal is: " << oct << n << endl;

    cout << "Press any key to continue...";

    cin.ignore( numeric_limits<streamsize>::max(), '\n' );

}
void O2D()
{
int i,OctNum,DecNum = 0,arr[20];

cout<< "\n Enter the octal value you wish to convert into decimal: ";
cin>>OctNum;

for(i=0; OctNum>0; i++) 
{
arr[i] = OctNum % 10;
OctNum = OctNum / 10;
}
cout<<i;

for(int power=0, j=0; j<i ; j++,power++)
{
DecNum = DecNum + arr[j] * pow(8.0,power);
}

cout<<"\n\n The decimal representation of the given octal is: "<<DecNum<<endl;

cin.get();


}
void O2H()
{

ULONG octalValue;
char choice = '1';
while(choice=='1') {
printf("\nEnter the octal value you wish to convert into hexadecimal: ");
scanf_s("%ld",&octalValue);
processEntry(octalValue);
printf("Press 1 to enter another value or press 0 to exit\n\n");
printf("Your Choice: ");
scanf_s(" %c",&choice);
}

}
void H2D()
{
 int x;
 cout << "\nEnter the hexadecimal value you wish to convert into decimal: " << endl<<endl;
    cin >> hex >> x;
cout<<endl;
    cout <<"\n The decimal representation of the given hexadecimal is: "<< x << endl<<endl;
}   
void H2O()
{
 int x;
 cout << "\nEnter the hexadecimal value you wish to convert into octal: " << endl<<endl;
    cin >> oct >> x;
cout<<endl;
    cout <<"\n The octal representation of the given hexadecimal is: "<< x << endl<<endl;
}   
void H2B()
{
char binNumber[MAX],hexDecimal[MAX];
    long int t=0;

    cout<<"Enter any hexadecimal number: ";
    cin>>hexDecimal;
    cout<<" Equivalent binary value: \n";
cout<<"\n";
    while(hexDecimal[t]){
         switch(hexDecimal[t]){
             case '0': cout<<("0000"); break;
             case '1': cout<<("0001"); break;
             case '2': cout<<("0010"); break;
             case '3': cout<<("0011"); break;
             case '4': cout<<("0100"); break;
             case '5': cout<<("0101"); break;
             case '6': cout<<("0110"); break;
             case '7': cout<<("0111"); break;
             case '8': cout<<("1000"); break;
             case '9': cout<<("1001"); break;
             case 'A': cout<<("1010"); break;
             case 'B': cout<<("1011"); break;
             case 'C': cout<<("1100"); break;
             case 'D': cout<<("1101"); break;
             case 'E': cout<<("1110"); break;
             case 'F': cout<<("1111"); break;
             case 'a': cout<<("1010"); break;
             case 'b': cout<<("1011"); break;
             case 'c': cout<<("1100"); break;
             case 'd': cout<<("1101"); break;
             case 'e': cout<<("1110"); break;
             case 'f': cout<<("1111 \n"); break;
             default:  cout<<"\nInvalid hexadecimal digit %c "<<hexDecimal[t]; 
         }
         t++;
    }    
}

The problem is under void H2O...

In line 307 you tell cin that you want to read octal values. Use the hex modifier instead, then use the oct modifier in the cout statement.

You might want to consider using a single more general conversion rather than all these custom conversions.
1) Determine the input base.
2) Read the value into an long integer.
3) Determine the output base.
4) Output the long integer using the given base.
That would be a lot simpler and have a lot less duplication that this.

Wow what a simple solution! I am a beginner at programming so a lot of times I don't realize the ridiculous mistakes I make while writing my code. Thank you for your help and thank you for your suggestions on simplifying my code. I appreciate it.

Well, I think there's no way to directly convert hex to octal because a hex value needs to be parsed first to get its value in real numbers (decimal). But the process is always the same: to convert decimal to another notation (hex, octal) you divide the number with your base (radix), putting the remainder right to left, until you get a zero quotient. Converting from other notation to decimal, start from 0, multiply it with 10 and parse and add the value of that notation starting from the left.

Here I'll show you some example: Note that numerical notations other than decimal can only be stored in strings (well, it's only my assumption and someone may correct me if I'm wrong).

  1. Converting decimal to dexadecimal

    const char * dectohex(long num)
    {
        static char szout[11];
        long c;
        int pos = 10;
        memset(szout, '0', 10);
        while( num )
        {
            c = num % 16;
            if( c<=9 )
                szout[pos--] = '0' + c;
            else
                szout[pos--] = 'A' + c;
            num /= 16;
        }
        szout[0] = '0';
        szout[1] = 'x';
        return szout;
    }
    
  2. Converting hex to decimal

    long hextodec(const char * szHex)
    {
        long ret = 0;
        char h;
        for( ;*szHex;*szHex++ )
        {
            h = tolower(*szHex);
            if( '0'<=h && h<='9' )
                ret = ret * 10 + (h - '0');
            else if( 'a'<=h && h<='f' )
                ret = ret * 10 + (10 + h - 'a');
            else
                break;
        }
        return ret;
    }
    

Edited 3 Years Ago by deceptikon: Fixed code formatting

Actually, the internal representation of an integer is in binary, not decimal, so your function names are misleading. You could easily expand the functions to other bases by passing the base to generate and making small modifications to the code. Make sure you check that the passed base is between 2 and 36; after 36 you run out of letters.

This question has already been answered. Start a new discussion instead.