我想知道为什么在将十六进制字符串(0x1)转换为uint8时得到0的结果.
我尝试使用boost::lexical_cast但是我得到了一个bad_lexical_cast例外.因此,我决定使用a stringstream而不是我得到的值不正确.
...
uint8_t temp;
std::string address_extension = "0x1";
std::cout << "Before: " << address_extension << std::endl;
StringToNumeric(address_extension, temp);
std::cout << "After: " << temp << std::endl;
...
template <typename T>
void StringToNumeric(const std::string& source, T& target)
{
//Check if source is hex
if(IsHexNotation(source))
{
std::stringstream ss;
//Put value in the stream
ss << std::hex << source;
//Stream the hex value into a target type
ss >> target;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以放心,它IsHexNotation()可以正常工作,并且不会在声明时更改源:
bool IsHexNotation(const std::string& source)
Run Code Online (Sandbox Code Playgroud)
将十六进制字符串转换为uint8的正确方法是什么(假设十六进制字符串适合数据类型)?
使用这样的代码对我有用:
std::stringstream ss;
int target(0);
ss << std::hex << source;
if (ss >> target) {
std::cout << "value=" << target << '\n';
}
else {
std::cout << "failed to read value\n";
}
Run Code Online (Sandbox Code Playgroud)
但是,我记得有一个关于写入后字符串流的读取位置应该在哪里的讨论.由于它主要遵循文件流模型,因此即使它是相同的位置,您也需要寻找所需的位置.一些实现使用公共位置,而其他实现使用单独的读取和写入位置.你可以尝试使用
ss.seekg(0, std::ios_base::beg);
Run Code Online (Sandbox Code Playgroud)
确保读取位置位于流的开头.另外,在我看来,最好是初始化std::istringstream并直接读取:
std::istringstream in(source);
if (in >> std::hex >> target) { ... }
Run Code Online (Sandbox Code Playgroud)
请注意,您始终要检查提取是否成功:这样您就会得到一个实际出错的提示,而值0可能只是变量的初始值.