简体   繁体   中英

Convert string into hex format and append “0x ” to hex value

I need to convert string to hex format and append "0x" prefix to hex value. For Example:

Input: std::string s = "0x06A4";

Output: int num = 0x06A4

I have tried this code:

{
    std::stringstream ss;
    std::string s = "0x06A4";
    int num = std::stoi(s, 0, 16);
    std::cout << "value in decimal     = " << num << '\n';
    std::cout << "value in hexadecimal = " << std::hex << num << '\n';
    ss << "0x" << std::hex << num << '\n'; //
    std::string res = ss.str();
    std::cout << "result  " << res << '\n';
}

@yogita, std::hex is just one of the configuration you need. You are probably missing the setfill and the setw configuration, as following:

#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
    std::stringstream ss;
    std::string s = "0x06A4";

    int num = std::stoi(s, nullptr, 16);
    std::cout << "value in decimal     = " << num << '\n';
    std::cout << "value in hexadecimal = " << std::hex << num << '\n';
    ss << "0x" << std::hex << std::setfill('0') << std::setw(4) <<num << '\n';

    std::string res = ss.str();
    std::cout << "result  " << res << '\n';
    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