23,121
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <iconv.h>
char* utf16ToUtf8(const wchar_t* ws, size_t wcharCount) {
static char buf[10001];
size_t dstlen = 10000;
iconv_t conv = iconv_open("UTF8", "UTF16");
if(conv==(iconv_t)-1) {
throw "utf16ToUtf8 conv -1";
}
size_t srcLen = wcharCount*2;
iconv(conv, (char**)&ws, &srcLen, (char**)&buf, &dstlen);
iconv_close(conv);
return buf;
}
void testUtf16ToUtf8() {
char data[]={0x00, 0x63, 0x00, 0x6f}; // "co" 的UTF16 字符串
//char data[]={0x63, 0x00, 0x6f, 0x00};
char* s = utf16ToUtf8((wchar_t*)data, 2);
printf("s:%s \n", s);
}
// 运行环境:ubuntu, 14.04
int main() {
try {
testUtf16ToUtf8();
return 0;
}
catch(...) {
printf("ERROR \n");
}
return -1;
}
#include <stdio.h>
#include <stdlib.h>
#include <iconv.h>
char* utf16ToUtf8(const wchar_t* ws, size_t wcharCount) {
static char buf[10001];
size_t dstlen = 10000;
iconv_t conv = iconv_open("UTF8", "UTF16");
if(conv==(iconv_t)-1) {
throw "utf16ToUtf8 conv -1";
}
size_t srcLen = wcharCount*2;
/*
from man: The inbuf argument is the address of a variable that points to the first character of the input sequence;
所以,为防万一,也声明一个变量保存ws
*/
char* src = (char*)ws;
char* outbuf = buf;
int ret = iconv(conv, (char**)&src, &srcLen, &outbuf , &dstlen);
printf("iconv ret:%d \n", ret);
iconv_close(conv);
return buf;
}
void testUtf16ToUtf8() {
//char data[]={0x00, 0x63, 0x00, 0x6f}; // "co" 的UTF16 字符串
//char data[]={0x63, 0x00, 0x6f, 0x00};
wchar_t data[] = L"中文12356";
char* s = utf16ToUtf8((wchar_t*)data, 7);
printf("s:%s \n", s);
}
//#include <locale.h>
// 运行环境:ubuntu, 14.04
int main() {
try {
//setlocale(LC_ALL, "C");
testUtf16ToUtf8();
return 0;
}
catch(const char* e) {
printf("ERROR:%s \n", e);
}
catch(...) {
printf("ERROR ");
}
return -1;
}
char *outbuf = buf;
iconv(conv, (char**)&ws, &srcLen, &outbuf , &dstlen);
char **outbuf = (char**)&buf;
iconv(conv, (char**)&ws, &srcLen, outbuf , &dstlen);