簡體   English   中英

將字符串轉換為十六進制格式,並將“0x”附加到十六進制值

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

我需要將字符串轉換為十六進制格式並將“0x”前綴附加到十六進制值。 例如:

輸入: std::string s = "0x06A4";

輸出: int num = 0x06A4

我試過這段代碼:

{
    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只是你需要的配置之一。 您可能缺少setfill和setw配置,如下所示:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM