Search code examples
c++opensslwidechar

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?


Solution

  • 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);