7

What's the simplest way to convert a Unicode codepoint into a UTF-8 byte sequence in C? The only way that springs to mind is using iconv to map from the UTF-32LE codepage to UTF-8, but that seems like overkill.

3
  • I ended up going with iconv anyway. It may seem like overkill, but it also seems like the only real solution without introducing external dependencies. Oct 27, 2008 at 19:53
  • So why not accept @JesperE's answer and upvote it.
    – tvanfosson
    Oct 27, 2008 at 19:55
  • 5
    I thought "no longer relevant" is used when a bug in a product is fixed, or better tool is introduced, not when asker is no longer interested in the answer...
    – buti-oxa
    Oct 27, 2008 at 21:06

3 Answers 3

8

Unicode conversion is not a simple task. Using iconv doesn't seem like overkill at all to me. Perhaps there is a library version of iconv you can use to avoid make a system() call, if that's what you want to avoid.

1
  • 1
    For this direction, it's an extremely simple task. No library is needed. Also, iconv refers to both a C interface and a utility program in POSIX. I suspect OP was talking about the C interface, which would be a very good option for this, but writing it yourself is also not difficult. It's the other direction (UTF-8 to codepoints) that's easy to mess up. May 24, 2011 at 14:15
5

Might I suggest ICU? It's a reasonably "industry standard" way of handling i18n issues.

I haven't used the C version myself, but I suspect ucnv_fromUnicode might be the function you're after.

1
  • I'm not going to introduce dependencies on a new set of non-system-provided libraries just for this task. Thanks for the suggestion, though. Oct 27, 2008 at 19:54
3

UTF8 works by coding the length of the encoded codepoint into the highest bits of the encoded bytes. see http://en.wikipedia.org/wiki/UTF-8#Description

I found this small function in C here http://www.deanlee.cn/programming/convert-unicode-to-utf8/ , didn't test it though.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.