write a program that converts a hex string into a decimal integer

Pages: 12
I was hoping that someone could show me how to convert a hex string into a decimal number. The book I'm using to teach myself says I need to Implement the parseHex function to throw a runtime_error exception if the string is not a hex string. Write a test program that prompts the user to enter a hex number as a string and display the number in decimal.

Could someone please show me what the book is asking me to do?
Do you know what a hexadecimal number is?
I kind of understand hex, but I'm not fluent by any means.
can someone please help?
The book I'm using to teach myself says I need to Implement the parseHex function to throw a runtime_error exception if the string is not a hex string.



Um... no... Please burn that book, and also post the title of it so that we may black list it. http://www.cplusplus.com/reference/clibrary/cctype/isxdigit/

EDIT: Unless it's asking you to use that function and throw a run_time exception. That would make a little more sense.
Last edited on
Well, ok, short explanation. A hexadecimal number is basically a base 16 number, meaning it has digits going from 0-15 (10-15 are represented by the letters a-f). A hex number consists of hex digits, which represent a power of 16 (starting at 16 power 0, usually ascending from right to left).

This means that 1AF in hexadecimal stands for 1*16^2(1*256) + 10*16^1(10*16) + 15*16^0(15*1). To convert a hex string to a deximal integer, we first check each character (at this point, you should automatically think "loop") for whether it is a legal character or not (which means, it may be either a digit from 0-9, a letter from a-f or a letter from A-F). Assuming that the string is encoded in ASCII, this means that a letter must either be in the range of 48-58 (digits 0-9), or in the range of 65-70 (letters A-F) or in the range 97-102 (letters a-f).

While we are at that, we can also start adding up the digits. Since a string is read from left to right, the first digit we encounter will be the highest power of 16, the last digit will be the 0th power of 16. Since we already know the size (length) of the string, we know that the first digit will be the (stringlength-1)th power of 16 (since the last digit is the 0th). Now, depending on whether it is a digit, an upper case letter or a lower case letter, we add (charactervalue-48) or (charactervalue-55) or (charactervalue-87) times the power of 16 to the sum.

At the end, we just return the sum. Try reading this carefully, if you get confused by anything, try drawing every single step on a sheet of paper before asking for help.

EDIT:

Um... no... Please burn that book, and also post the title of it so that we may black list it.

So, uh, exercises - this is obviously one- are a bad thing in a teaching book? What the heck?
Last edited on
That's a very good explaination on how someone would go about converting hex to decimal. Personally I like to use 'setf(...)' http://www.cplusplus.com/reference/iostream/ios_base/setf/

;D
Last edited on
are the for or foreach loops the same in c++ as in c#?
@ hanst99: I just think that if a book is going to teach you how to do something it should let you know what tools you have at your disposal. Also stuff like this let's people think that they HAVE to do stuff the hard way, it never shows them there is a better alternative.
Also stuff like this let's people think that they HAVE to do stuff the hard way, it never shows them there is a better alternative


I don't think so. A book that only teaches the C++ language can do that, but most books also aim to teach programming (actually, all books that are aimed at beginners do that). Programming is essentially problem solving, so on regular occasions those books will provide exercises that the reader should be able to solve with the knowledge he or she has learned so far. Being told how to use library functions doesn't make anyone a programmer, let alone a good one. Of course a good book would on the occasion also mention that there already is a standard function that provides such functionality- after the student has completed the exercise.

What you are talking about is a reference manual, which is completely useless to someone who has never written a single program in his life. Teaching books are no reference manuals, most books will mention this and I think that the average person also knows this.
Last edited on
are the for or foreach loops the same in c++ as in c#?

Not necessarily. This website has a C++ tutorial, (in the documentation tab on the left side), you might wanna check out the subsection on loops. Though you will probably find that they work very similarily, the syntax might be different. But I can't tell you for sure, I have never worked with C# myself. Though it supposedly has a very similar syntax to C/C++ so the difference will probably be very small, if there even is one.
Last edited on
There are for loops, but no foreach loops (yet). The closest you can get to a foreach loop in C++ is Boost's macro FOREACH, which isn't quite a part of standard C++. :(

http://www.boost.org/doc/libs/1_46_1/doc/html/foreach.html

-Albatross
There is also a for_each algorithm in the STL, which is standard. Ok admitted, that's not quite the same thing as how you normally write a loop, but it does what it says it does.
Last edited on
The following is my code for this project and it seems to work fairly well. Now I would like to know how to change this code to make it convert from binary to decimal... Can you point me in the right direction?


#include <iostream>
#include <string>
#include <cstring> // For toupper function - changes lowercase to uppercase
using namespace std;

int hexToDec(const string &hex);

int hexCharToDec(char ch);

int main()
{
cout << "Enter a hex number: ";
string hex;
cin >> hex;

int decimal = -1;
decimal = hexToDec(hex);

if (decimal != -1)
cout << "The decimal value for hex number " << hex << " is " << decimal << endl;

cin.get();
cin.get();

return 0;
}

int hexToDec(const string &hex)
{
int decimalValue = 0;

for (int index = 0; index < hex.size(); index++)
{
try
{
char ch = toupper(hex[index]);

//Throw an exception if not a hex string
if (!(ch >= 'A' && ch <= 'F' || ch >= '0' && ch <= '9'))
{
throw runtime_error("String is not a hex string");
}
else
decimalValue = decimalValue * 16 + hexCharToDec(hex[index]);
}
catch (runtime_error e)
{
cout << e.what();
return -1;
}
}

return decimalValue;
}

int hexCharToDec(char ch)
{
ch = toupper(ch);
if (ch >= 'A' && ch <= 'F')
return 10 + ch - 'A';
else
return ch - '0';
}
I would put your try-catch block into your main. The whole purpose of the exception system is to seperate the code that handles exceptions from the code that causes them (well, at least that is one major advantage of it). Other than that, your code also doesn't work right now. See what converting "1FF" will output for you. I could bet it will output 527, instead of 4351 as it should.

Other than that, binary conversion basically works the same way, with the difference that binary numbers are base 2, not base 16. Because of that it's even easier to handle, because you don't actually need to multiply your numbers with anything (though if you do, you could actually let binary and hex conversions be performed by the same function without much additional code).
so 10101
would be
2^4+2^2+2^0, which is 21.
Last edited on
1ff was actually 511... what did I do wrong in my code?
Damn, I forgot one multiplication by 16... wait, let's stay on topic. Your calculation is wrong:
decimalValue * 16 + hexCharToDec(hex[index]);
needs to be
decimalValue + pow(16,hex.size()-index-1) * hexCharToDec(hex[index]);

You need to include cmath for the pow function though.
Last edited on
I included cmath, but pow is still giving me an error. Are you sure cmath is the right library for the pow function?
http://www.cplusplus.com/reference/clibrary/cmath/

Yes I am. Maybe you mispelled cmath or something?
#include <cmath>

right? The error says more than one instance of overloaded function "pow" matches the argument list... ideas?
Pages: 12