转换“const wchar_t *”到“unsigned char *”
在 C++ 中,是否可以将“const wchar_t *”转换为“unsigned char *”?
我怎样才能做到这一点?
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 );
In C++ is it possible to convert a 'const wchar_t *' to 'unsigned char *'?
How can I do that?
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 );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要逐个字符进行转换。有像
wcstombs
这样的函数可以做到这一点。You need to convert character by character. There are functions like
wcstombs
to do this.尝试使用reinterpret_cast。所以:
这可能不起作用,因为 c_str 返回一个 const wchar_t *所以你也可以尝试:
这是可行的,因为 hmac_sha256_init 应该接受二进制 blob 作为其输入,因此 dirName 中包含的 unicode 字符串是可接受的哈希输入。
但是您的代码中有一个错误 - dirName.length() 返回的长度是字符数,而不是字节数。这意味着传递给 hmac_sha256_init 的字节太少,因为您将 unicode 字符串作为二进制 blob 传递,因此您需要将 (dirName.length()) 乘以 2。
Try using reinterpret_cast. So:
That might not work because c_str returns a const wchar_t *so you can also try:
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.
由于您使用的是 WinAPI,因此请使用
WideCharToMultiByte
。Since you're using WinAPI, use
WideCharToMultiByte
.