简体   繁体   中英

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?

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 (ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM