Home > other >  String to Hex without changing number, C
String to Hex without changing number, C

Time:01-13

While working on a project, I found myself wondering how to convert from string to hex. Not just converting from, let's say, the string "42" to hex 0x3432.

I'm curious how you would go about converting the string "0x42" to hex 0x42. As in, assume the string given is a valid hex number (I know that's a big assumption, but go with it...). I want to use that as a hex number, not as a string anymore. How would I go about doing that conversion?

This isn't something I'd do... I'm just more curious if and how it would be done, as I've never run into this type of problem until now.

*Using C and C

CodePudding user response:

As this is just a matter of different representations of the same value, its IO streams that offer such "conversion":

#include <sstream>
#include <iostream>

int main() {
    std::stringstream ss{"0x42"};
    int x = 0;
    ss >> std::hex >> x;
    std::cout << x << "\n";
    std::cout << std::hex << x;
}

Output:

66
42

CodePudding user response:

Like this:

#include <string>
#include <iostream>

int main()
{
    std::string s = "0x42";
    int i = std::stoi( s, nullptr, 16 );
    int j = strtoul( s.substr(2).c_str(), nullptr, 16 );
    std::cout << i << "," << j << "\n";
}

Note that std::stoi will handle the leading "0x". strtoul is pickier.

  •  Tags:  
  • Related