简体   繁体   中英

How to convert string into hex value

I am trying to convert string value into its hex form, but not able to do. Following is the C++ code snippet, with which I am trying to do.

#include <stdio.h>
#include <sys/types.h>
#include <string>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

using namespace std;

int main()
{

    string hexstr;
    hexstr = "000005F5E101";
    uint64_t Value;
    sscanf(hexstr.c_str(), "%" PRIu64 "", &Value);
    printf("value = %" PRIu64 " \n", Value);

    return 0;
}

The Output is only 5, which is not correct.

Any help would be highly appreciated. Thanks, Yuvi

If you're writing C++, why would you even consider using sscanf and printf ? Avoid the pain and just use a stringstream :

int main() { 

    std::istringstream buffer("000005F5E101");

    unsigned long long value;

    buffer >> std::hex >> value;

    std::cout << std::hex << value;
    return 0;
}
#include <sstream>
#include <string>

using namespace std;

int main(){

  string myString = "45";
  istringstream buffer(myString);
  uint64_t value;
  buffer >> std::hex >> value;

  return 0;
}

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