I've been writing a program that will convert a decimal input to an octal or hex number. Basically I just need some help with the decimal to hex conversion. I searched the board for a while, but couldnt find anything...(I'm new to C++, so it might be that i just dont understand it.) Here's my code so far, thanks for any help!
Code:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
enum ConverstionType {NONE,DECIMAL,HEX,OCTAL};
int number = 0;// a global variable visible throughout the file
int test = NONE;
// this function converts a char to upper case
// and display it if not a digit representation;
void asciiToInt(char aChar){
int digitValue = 0;
switch(::test) {
case OCTAL: {
digitValue = aChar - '0';
::number *= 8;
::number += digitValue;
break;
}
case DECIMAL:
{
digitValue = aChar - '0';
::number *= 10;
::number += digitValue;
break;
}
case HEX:
{if (aChar >= 'a' && aChar <= 'f')
digitValue = aChar - 'a' + 10;
else
digitValue = aChar - '0';
::number *= 16;
::number += digitValue;
break;
}
default: {
cout << "error in conversion" << endl;
::number = 0;
}
}
}
int main(){
string word;
cout << "enter a number:";
getline(cin,word);
if(word[0] == '0')
::test = OCTAL;
else if(word[1] == 'x')
::test = HEX;
else
::test = DECIMAL;
cout << word << endl;
// apply the function showChar to each character in the string
for_each(word.begin(),word.end(),asciiToInt);
cout << "converted number is " << number << endl;
return 0;
}