[英]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. 我需要将字符串转换为十六进制格式并将“0x”前缀附加到十六进制值。 For Example: 例如:
Input: std::string s = "0x06A4";
输入: std::string s = "0x06A4";
Output: int num = 0x06A4
输出: 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. @ yogita,std :: hex只是你需要的配置之一。 You are probably missing the setfill and the setw configuration, as following: 您可能缺少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.