[英]Convert Hex to Byte in C++
How do you convert a hex string to short in c++? 如何在C ++中将十六进制字符串转换为short?
Let's say you have 假设您有
string hexByte = "7F";
How do you convert that to a byte? 您如何将其转换为字节? Which I assume it's a char or int8_t in c++ 我认为这是C ++中的char或int8_t
I tried: 我试过了:
wstring hexString = "7F";
unsigned char byte;
stringstream convert(hexString);
convert >> byte;
// 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/ http://www.cplusplus.com/reference/locale/wstring_convert/to_bytes/
Convert each character of hex input to integer type 将十六进制输入的每个字符转换为整数类型
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.