如何在c ++中将十六进制字符串转换为short?
假设你有
string hexByte = "7F";
如何将其转换为字节?我认为它在c ++中是 char 或 int8_t
我试过了:
wstring hexString = "7F";
unsigned char byte;
stringstream convert(hexString);
convert >> byte;
答案 0 :(得分:2)
// converting from UTF-16 to UTF-8
#include <iostream> // std::cout, std::hex
#include <string> // std::string, std::u16string
#include <locale> // std::wstring_convert
#include <codecvt> // std::codecvt_utf8_utf16
int main ()
{
std::u16string str16 (u"\u3084\u3042"); // UTF-16 for YAA (やあ)
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> cv;
std::string str8 = cv.to_bytes(str16);
std::cout << std::hex;
std::cout << "UTF-8: ";
for (char c : str8)
std::cout << '[' << int(static_cast<unsigned char>(c)) << ']';
std::cout << '\n';
return 0;
}
http://www.cplusplus.com/reference/locale/wstring_convert/to_bytes/
答案 1 :(得分:0)
将十六进制输入的每个字符转换为整数类型
int char2int(char input)
{
if(input >= '0' && input <= '9')
return input - '0';
if(input >= 'A' && input <= 'F')
return input - 'A' + 10;
if(input >= 'a' && input <= 'f')
return input - 'a' + 10;
throw std::invalid_argument("Invalid input string");
}
// This function assumes src to be a zero terminated sanitized string with
// an even number of [0-9a-f] characters, and target to be sufficiently large
void hex2bin(const char* src, char* target)
{
while(*src && src[1])
{
*(target++) = char2int(*src)*16 + char2int(src[1]);
src += 2;
}
}