Convert a 'const wchar_t *' to 'unsigned char *'

前端 未结 3 1766
鱼传尺愫
鱼传尺愫 2021-01-19 18:41

In C++ is it possible to convert a \'const wchar_t *\' to \'unsigned char *\'?

How can I do that?

wstring dirName;
unsigned char* dirNameA = (unsigne         


        
相关标签:
3条回答
  • 2021-01-19 19:04

    Try using reinterpret_cast. So:

    unsigned char * dirNameA = reinterpret_cast<unsigned char *>(dirName.c_str());
    

    That might not work because c_str returns a const wchar_t *so you can also try:

    unsigned char * dirNameA = reinterpret_cast<unsigned char *>(
                                   const_cast<wchar_t *>(dirName.c_str())
                               );
    

    This works because hmac_sha256_init should accept a binary blob as its input, so the unicode string contained in dirName is an acceptable hash input.

    But there's a bug in your code - the length returned by dirName.length() is a count of characters, not a count of bytes. That means that passing too few bytes to hmac_sha256_init since you're passing in a unicode string as a binary blob, so you need to multiply (dirName.length()) by 2.

    0 讨论(0)
  • 2021-01-19 19:06

    Since you're using WinAPI, use WideCharToMultiByte.

    0 讨论(0)
  • 2021-01-19 19:16

    You need to convert character by character. There are functions like wcstombs to do this.

    0 讨论(0)
提交回复
热议问题