I would like to know why I am getting the result of 0 when converting a hex string (0x1) to a uint8.
I tried to use boost::lexical_cast
but I get a bad_lexical_cast
exception. Therefore, I decided to use a stringstream
instead but I am getting the incorrect value.
...
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;
}
}
You can be assured that IsHexNotation()
works correctly and does not change the source as it is declared:
bool IsHexNotation(const std::string& source)
What is the correct way to convert a hex string to a uint8 (given that the hex string WILL fit into the datatype)?
Using code like this works for me:
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";
}
However, I remember that there was a discussion on where the read position of a string stream should be after a write. Since it mostly follows the model of file streams, you'd need to seek to desired position, even if it is the same position. Some implementations used a common position and others used separate read and write positions. You can try using
ss.seekg(0, std::ios_base::beg);
to make sure that the read position is at the start of the stream. Alternatively, and in my opinion preferable, is to initialize an std::istringstream
and read from that directly:
std::istringstream in(source);
if (in >> std::hex >> target) { ... }
Note, that you always want to check if the extraction was successful: this way you get a hint that something actually went wrong and the value 0
may be just some initial value of the variable.
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.