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

In C ++ can I convert 'const wchar_t *' to 'unsigned char *'?

How can i do this?

wstring dirName; unsigned char* dirNameA = (unsigned char*)dirName.c_str(); // I am creating a hash from a string hmac_sha256_init( hash, (unsigned char*)dirName.c_str(), (dirName.length)+1 ); 
+4
source share
3 answers

Try using reinterpret_cast. So:

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

This may not work because c_str returns 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 binary blob as its input, so the unicode string contained in dirName is a valid hash input.

But there is an error in your code - the length returned by dirName.length () is the number of characters, not the number of bytes. This means passing too many bytes to hmac_sha256_init, since you are passing the unicode string as a binary blob, so you need to multiply (dirName.length ()) by 2.

+1
source

You need to convert character by character. There are features like wcstombs .

+1
source

Since you are using WinAPI, use WideCharToMultiByte .

+1
source

All Articles