2010-04-11 5 views
0

J'ai un exemple d'adresse: 0x003533, c'est une chaîne de caractères mais pour l'utiliser j'ai besoin d'être LONG mais je ne sais pas comment le faire: S a quelqu'un une solution?C++ adresse chaîne -> long

donc chaîne: "0x003533" à long 0x003533 ??

Répondre

5

Utilisation strtol() comme dans:

 
#include <cstdlib> 
#include <string> 

// ... 
{ 
    // ... 
    // Assume str is an std::string containing the value 
    long value = strtol(str.c_str(),0,0); 
    // ... 
} 
// ... 
3
#include <iostream> 
#include <sstream> 
#include <string> 

using namespace std; 

int main() { 
    string s("0x003533"); 
    long x; 
    istringstream(s) >> hex >> x; 
    cout << hex << x << endl; // prints 3533 
    cout << dec << x << endl; // prints 13619 
} 

EDIT:

Comme Potatocorn dit dans les commentaires, vous pouvez également utiliser boost::lexical_cast comme indiqué ci-dessous:

long x = 0L; 
try { 
    x = lexical_cast<long>("0x003533"); 
} 
catch(bad_lexical_cast const & blc) { 
    // handle the exception 
} 
+0

Alias 'boost :: lexical_cast' – Potatoswatter