coder
coder

Reputation: 1079

how to convert a hexadecimal string to a corresponding integer in c++?

i have a unicode mapping stored in a file.

like this line below with tab delimited.

a   0B85    0   0B85

second column is a unicode character. i want to convert that to 0x0B85 which is to be stored in int variable.

how to do it?

Upvotes: 2

Views: 769

Answers (2)

Todd Gamblin
Todd Gamblin

Reputation: 59827

You could use strtol, which can parse numbers into longs, which you can then assign to your int. strtol can parse numbers with any radix from 2 to 36 (i.e. any radix that can be represented with alphanumeric charaters).

For example:

#include <cstdlib>
using namespace std;

char *token;
...
// assign data from your file to token
...

char *err;   // points to location of error, or final '\0' if no error.
int x = strtol(token, &err, 16);   // convert hex string to int

Upvotes: 6

Eli Bendersky
Eli Bendersky

Reputation: 273456

You've asked for C++, so here is the canonical C++ solution using streams:

#include <iostream>

int main()
{
    int p;
    std::cin >> std::hex >> p;
    std::cout << "Got " << p << std::endl;
    return 0;
}

You can substitute std::cin for a string-stream if that's required in your case.

Upvotes: 7

Related Questions