0

我想知道为什么在将十六进制字符串 (0x1) 转换为 uint8 时得到 0 的结果。

我尝试使用boost::lexical_cast,但出现bad_lexical_cast异常。因此,我决定改用 astringstream但我得到的值不正确。

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

 }

您可以放心,它IsHexNotation()可以正常工作并且不会更改声明的源:

bool IsHexNotation(const std::string& source)

将十六进制字符串转换为 uint8 的正确方法是什么(假设十六进制字符串将适合数据类型)?

4

1 回答 1

5

使用这样的代码对我有用:

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

但是,我记得有一个关于字符串流的读取位置应该在写入之后的讨论。由于它主要遵循文件流的模型,因此您需要寻找所需的位置,即使它是相同的位置。一些实现使用公共位置,而其他实现使用单独的读取和写入位置。您可以尝试使用

ss.seekg(0, std::ios_base::beg);

确保读取位置位于流的开头。或者,在我看来更可取的是初始化一个std::istringstream并直接从中读取:

std::istringstream in(source);
if (in >> std::hex >> target) { ... }

请注意,您总是想检查提取是否成功:这样您会得到一个提示,表明确实出了问题,并且该值0可能只是变量的一些初始值。

于 2013-08-21T00:19:31.590 回答