将C ++ std :: string转换为UTF-16-LE编码的字符串 [英] Convert C++ std::string to UTF-16-LE encoded string
问题描述
我今天一直在搜索数小时,但找不到适合我的任何内容.我刚刚看过的一个没有运气的是"
I've been searching for hours today and just can't find anything that works out for me. The one I've just had a look at, with no luck, is "How to convert UTF-8 encoded std::string to UTF-16 std::string".
我的问题是,有一个简短的解释:
My question is, with a brief explanation:
我想在std C ++中创建有效的NTLM哈希,并且我正在使用OpenSSL的库通过其MD4例程创建哈希.我知道该怎么做,所以有人知道如何将std::string
转换为UTF-16 LE编码的字符串,我可以将其传递给MD4函数以获取正确的摘要吗?
I want to make a valid NTLM hash in std C++, and I'm using OpenSSL's library to create the hash using its MD4 routines. I know how to do that, so does anyone know how to convert the std::string
into a UTF-16 LE encoded string which I can pass to the MD4 functions to get a correct digest?
所以,我可以有一个保存char
类型的std::string
并将其转换为UTF16-LE编码的可变长度std :: string_type吗?是std::u16string
还是std::wstring
?
So, can I have a std::string
which holds the char
type, and convert it to a UTF16-LE encoded variable length std::string_type? Whether that be std::u16string
, or std::wstring
?
我会使用s.c_str()
还是s.data()
,并且在两种情况下length()
函数都能正确报告吗?
And would I use s.c_str()
or s.data()
and would the length()
function report correctly in both cases?
推荐答案
道歉,第一手……这将是一个很丑陋的答复,带有一些长代码.我最终使用了以下功能,同时按文件将iconv
有效地编译到Windows应用程序文件中:)
Apologies, firsthand... this will be an ugly reply with some long code. I ended up using the following function, while effectively compiling in iconv
into my windows application file by file :)
希望这会有所帮助.
char* conver(const char* in, size_t in_len, size_t* used_len)
{
const int CC_MUL = 2; // 16 bit
setlocale(LC_ALL, "");
char* t1 = setlocale(LC_CTYPE, "");
char* locn = (char*)calloc(strlen(t1) + 1, sizeof(char));
if(locn == NULL)
{
return 0;
}
strcpy(locn, t1);
const char* enc = strchr(locn, '.') + 1;
#if _WINDOWS
std::string win = "WINDOWS-";
win += enc;
enc = win.c_str();
#endif
iconv_t foo = iconv_open("UTF-16LE", enc);
if(foo == (void*)-1)
{
if (errno == EINVAL)
{
fprintf(stderr, "Conversion from %s is not supported\n", enc);
}
else
{
fprintf(stderr, "Initialization failure:\n");
}
free(locn);
return 0;
}
size_t out_len = CC_MUL * in_len;
size_t saved_in_len = in_len;
iconv(foo, NULL, NULL, NULL, NULL);
char* converted = (char*)calloc(out_len, sizeof(char));
char *converted_start = converted;
char* t = const_cast<char*>(in);
int ret = iconv(foo,
&t,
&in_len,
&converted,
&out_len);
iconv_close(foo);
*used_len = CC_MUL * saved_in_len - out_len;
if(ret == -1)
{
switch(errno)
{
case EILSEQ:
fprintf(stderr, "EILSEQ\n");
break;
case EINVAL:
fprintf(stderr, "EINVAL\n");
break;
}
perror("iconv");
free(locn);
return 0;
}
else
{
free(locn);
return converted_start;
}
}
这篇关于将C ++ std :: string转换为UTF-16-LE编码的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!