Skip to content

Instantly share code, notes, and snippets.

@suapapa
Created April 13, 2012 05:38
Show Gist options
  • Save suapapa/2374101 to your computer and use it in GitHub Desktop.
Save suapapa/2374101 to your computer and use it in GitHub Desktop.
iconv utf8 to ucs2 example
#include <stdio.h>
#include <iconv.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
int conv_utf8_to_ucs2(const char* src, size_t len)
{
iconv_t cb = iconv_open("UTF-16", "UTF-8");
if (cb == (iconv_t)(-1))
return 0;
uint16_t* outBuff = new uint16_t[len + 1];
char* pout = (char*) outBuff;
size_t inRemains = len;
size_t outRemains = len * sizeof(uint16_t);
printf("inRemains:%d outRemains:%d\n", (int)inRemains, (int)outRemains);
size_t cvtlen = iconv(cb, (char**)&src, (size_t*)&inRemains, (char**)&pout, (size_t*)&outRemains);
if (cvtlen == (size_t) - 1) {
printf("error:%s, %d\n", strerror(errno), errno);
goto out;
}
*pout = 0;
printf("inRemains:%d outRemains:%d cvtlen:%d\n", (int)inRemains, (int)outRemains, (int)cvtlen);
for (int i = 0; (i < len) && outBuff[i] ; i++)
printf("0x%04x\n", outBuff[i]);
out:
if(outBuff)
delete[] outBuff;
iconv_close(cb);
return 0;
}
int main(int argc, char** argv)
{
char utf8_str[] = "안녕 세상아?";
int len = strlen(utf8_str);
conv_utf8_to_ucs2(utf8_str, len);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment