# string to hex

• 05-06-2005
LogicError
string to hex
I'm doing a game in SDL and the FillRect function takes a hex value (color) as a parameter.. I have scripts stored in external files with functions such as ClearScreen(#FFFFFF); .. I need to convert the "#FFFFFF" to real hex #FFFFFF .. thanks for your help
• 05-06-2005
pianorain
You mean like 0xFFFFFF?
• 05-06-2005
joshdick
You can use sprintf() to do it, or you can use a stringstream.
• 05-06-2005
DougDbug
I don't think you really want to convert TO hex... You want to convert FROM hex.
This can get confusing...

Firstly, you don't want to change it to hex. What you really want to do is change the string-in-hex-format (#FFFFFF) to an integer (which has a value equal to FFFFFF hex).

You can't really change a number to hex. Once a number gets into the computers memory its just a number, and all numbers are actually stored in binary. You can save it as a string that looks like a hex number, but it will be saved in binary numbers that represent the ASCII characters.

This means that conversion only happens during input/output or when converting a string representation of the number (in some base) to a number, and vise-versa.

You can input an octal number, a decimal number, and a hex number. Later you can add the three numbers together without worring about the fact that they were input in different bases! You can display the result in any base you wish!

Don't forget to strip-out the leading "#' character before converting.

I don't have a stringstream example for you, but I think it's similar to this code fragment which treats an entered number as hex:
Code:

```cout << "Enter a Hex number: "; cin >> hex >> x;```
Here's an example using the C function strtoul() (I think it's from <cstdlib.h> )
Code:

```int x ; int Base = 16 ; char InputString[40]; char *pEnd = NULL;          // Required for Strtoul() cout << "Number? "; cin >> InputString; x = (int)strtol(InputString, &pEnd, Base);    // String to long```
I might be missing something, but I don't think sprintf() will help... It can convert a number to a string... We're trying to go the other way 'round.