简体   繁体   中英

unsigned char array to wide char array/string

How can/should I cast from a unsigned char array to a widechar array wchar_t or std::wstring ? And how can I convert it back to a unsigned char array?

Or can OpenSSL produce a widechar hash from SHA256_Update ?

Try the following:

#include <cstdlib>
using namespace std;

unsigned char* temp; // pointer to initial data
// memory allocation and filling
// calculation of string length

wchar_t* wData = new wchar_t[len+1];
mbstowcs(&wData[0], &temp1[0], len);

Сoncerning inverse casting look the example here or just use mbstowcs once again but with changing places of two first arguments.

Also WideCharToMultiByte function can be useful for Windows development, and setting locale should be considered as well (see some examples).

UPDATE:

To calculate length of string pointed by unsigned char* temp the following approach can be used:

const char* ccp = reinterpret_cast<const char*>(temp);
size_t len = mbstowcs(nullptr, &ccp[0], 0);
std::setlocale(LC_ALL, "en_US.utf8");
const char* mbstr = "hello";
std::mbstate_t state = std::mbstate_t();
// calc length
int len = 1 + std::mbsrtowcs(nullptr, &mbstr, 0, &state);
std::vector<wchar_t> wstr(len);
std::mbsrtowcs(&wstr[0], &mbstr, wstr.size(), &state);

How can/should I cast from a unsigned char array to a widechar array wchar_t or std::wstring? And how can I convert it back to a unsigned char array?

They are completely different, so you should not be doing it under most circumstances. If you provide a specific question with real code, than we can probably tell you more.


Or can OpenSSL produce a widechar hash from SHA256_Update?

No, OpenSSL cannot do this. It produces hashes which are binary strings cmposed of bytes, not chars. You are responsible for for presentation details, like narrow/wide character sets or base64 encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM