Last active
October 27, 2018 09:49
-
-
Save hoyang/7ea1f5c11ad77680f5bdfc37c1b0b8ac to your computer and use it in GitHub Desktop.
wstring to hex, hex to wstring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int encode(std::string* t, std::wstring s) | |
{ | |
std::wcout.imbue(std::locale("russian_russia.866")); | |
std::wcout << L"ENCODE: строка до:\t\t" << s << std::endl; | |
size_t i_len = s.length(); | |
std::stringstream ss; | |
std::wcout << L"ENCODE: Длина строки:\t\t" << i_len << std::endl; | |
ss << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << i_len * 2; | |
std::wcout << L"ENCODE: Необходимая длина(hex):\t" << i_len * 2 << std::endl; | |
for (size_t i = 0; i < i_len; ++i) | |
ss << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << s[i]; | |
t->append(ss.str()); | |
std::wcout << L"ENCODE: строка после(hex):\t" << t->c_str() << std::endl; | |
return (int)i_len * 2; | |
} | |
int decode(std::string s, std::wstring t) | |
{ | |
std::wcout.imbue(std::locale("russian_russia.866")); | |
std::wcout << L"DECODE: строка до(hex):\t\t" << s.c_str() << std::endl; | |
int i_len = 0; | |
std::stringstream ss(s.substr(0, 2)); | |
ss >> std::hex >> i_len; | |
std::wcout << L"DECODE: Длина строки(hex):\t" << i_len << std::endl; | |
std::wcout << L"DECODE: Необходимая длина:\t" << i_len / 2 << std::endl; | |
int i_char;// = 0; | |
std::wstringstream tss; | |
for (int i = 0; i < i_len / 2; ++i) | |
{ | |
ss.clear(); | |
ss.str(s.substr(2 + i * 2, 2)); | |
ss >> std::uppercase >> std::hex >> i_char; | |
tss << (TCHAR)i_char; | |
} | |
t = tss.str(); | |
std::wcout << L"DECODE: строка после:\t\t" << t << std::endl; | |
return i_len; | |
} | |
int _tmain(int argc, _TCHAR* argv[]) | |
{ | |
std::string source; | |
std::wstring msg_in; | |
std::wstring msg_out; | |
msg_in = L"Привет"; | |
encode(&source, msg_in); | |
std::cout << std::endl<< std::endl ; | |
decode(source, msg_out); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment