1

I want to know how to convert something like string x = "1f" to int y = 0x1f, every topic I found was solved by turning it to simply the integer value of it (31) or turning the string to a hexadecimal equivalent "Hello" > 48656C6C6F

std::stringstream Strm;
std::string Stng = "1f";
Strm << Stng;
int Hexa;
Strm >> std::hex >> Hexa;
cout << Hexa;

This closest I could get to it (but turned out it just converts it to integer)

EDIT: I guess my problem was I didn't know it must be stored as an integer and can be only shown as hexadecimal if i add std::hex after cout, that was stupid sorry

4
  • are you just looking to print the number in base 16? if so: cout << std::hex << Hexa. Note: "int y = 0x1f" translates to 00000000 00000000 00000000 00011111 (assuming 32bit int) as far as the processor is concerned. Commented May 3, 2013 at 20:54
  • 3
    "it just converts it to integer" — this is to be expected. There are no such things as hexadecimal integers. Commented May 3, 2013 at 20:56
  • 1
    int y = 0x1f and int y = 31 are identical. int has no notion of the base you express it in. Commented May 3, 2013 at 20:56
  • 2
    0x1F and 31 are both the same integer. Why do this cause so much confusion? Commented May 3, 2013 at 20:59

3 Answers 3

1

Integers don't carry labels saying 'I'm a decimal integer' or 'I'm a hexadecimal integer'. All integers are the same. So if you have found some code that converts a hexadecimal string to an integer then that is the code you should use.

Once you have your integer you can then choose to print it out in hexadecimal if you want. You do that with hex

int hexa = ...;
cout << hex << hexa; // prints an int in hexadecimal form
Sign up to request clarification or add additional context in comments.

Comments

0

One quite fast solutions is using boost::lexical cast. You can find everything here http://www.boost.org/doc/libs/1_53_0/doc/html/boost_lexical_cast.html

Comments

0

You have two choices:

  1. std::strtol
  2. std::stoi

The last will throw an exception if the input string is not a proper hexadecimal number.

And remember, in the computer all integers are stored in binary, hexadecimal is just a presentation. For example, the ASCII character 'a' is the same as decimal number 97 and the same as octal number 141 and the same as hexadecimal number 61 and the same as binary number (which it is ultimately is stored as in memory) 01100001.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.