Your first code doesn't work because there is no standard conversion operator defined for converting a std::string
to a unsigned char
. You need to actually parse the std::string
into a numeric value.
Your second code doesn't work because your std::stringstream
is not in std::hex
mode when reading decimal
from the stream, but even if it were, operator>>
treats an unsigned char
as a text character, not as an integer (same with operator<<
for output). So you need to use an actual integer type, such as short
or int
, which can hold the full value of the parsed numeric, eg:
string hex_str = "0x3d";
unsigned short temp;
stringstream my_ss;
my_ss << hex_str;
my_ss >> hex >> temp;
unsigned char decimal = temp;
That being said, I would suggest using std::istringstream
instead, eg:
#include <string>
#include <sstream>
#include <iomanip>
std::string a = "0x08";
unsigned short temp;
std::istringstream(a) >> std::hex >> temp;
BYTE Sample2 = static_cast<BYTE>(temp);
Demo
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
int main()
{
std::string hex_str = "0x3d";
unsigned short temp;
std::istringstream(hex_str) >> std::hex >> temp;
unsigned char decimal = static_cast<unsigned char>(temp);
std::cout << "The value is: " << static_cast<int>(decimal);
return 0;
}
Demo
Or, in C++11 and later, you can use std::stoi()
instead, eg:
#include <string>
std::string a = "0x08";
BYTE Sample2 = static_cast<BYTE>(std::stoi(a, nullptr, 16));
Demo
#include <iostream>
#include <string>
int main()
{
std::string hex_str = "0x3d";
unsigned char decimal = static_cast<unsigned char>(std::stoi(hex_str, nullptr, 16));
std::cout << "The value is: " << static_cast<int>(decimal);
return 0;
}
Demo