[英]Convert Hex to Byte in C++
如何在C ++中將十六進制字符串轉換為short?
假設您有
string hexByte = "7F";
您如何將其轉換為字節? 我認為這是C ++中的char或int8_t
我試過了:
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/
將十六進制輸入的每個字符轉換為整數類型
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.