Skip to content

Instantly share code, notes, and snippets.

@marcomaggi
Created August 27, 2013 08:39
Show Gist options
  • Save marcomaggi/6351143 to your computer and use it in GitHub Desktop.
Save marcomaggi/6351143 to your computer and use it in GitHub Desktop.
/* Demo for Libiconv. A simple example to demonstrate the use of
"UCS-4-INTERNAL": convert a string in UTF-8 encoding to an array of
integers representing Unicode code points. To compile the program
with Libiconv on a GNU+Linux system:
$ gcc -o iconv-demo iconv-demo.c -l iconv
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <iconv.h>
static void
logmsg (const char * message)
{
fprintf(stderr, message);
fprintf(stderr, "\n");
}
int
main (int argc, const char *const argv[])
{
iconv_t context;
context = iconv_open("UCS-4-INTERNAL", "US-ASCII");
if (((iconv_t)(-1)) == context) {
logmsg("error initialising context");
goto error;
}
{
char * in_buffer = "ciao";
size_t in_bytes_left = strlen(in_buffer);
uint32_t ou_bytes[4] = { -1, -1, -1, -1 };
size_t ou_bytes_left = sizeof(uint32_t) * 4;
char * ou_buffer = (char*)&ou_bytes;
size_t rv;
errno = 0;
rv = iconv(context,
&in_buffer, &in_bytes_left,
&ou_buffer, &ou_bytes_left);
if (((size_t)-1) == rv) {
logmsg("error converting");
goto context_error;
} else {
/* The output for the input "ciao" should be: 99, 105, 97, 111. */
printf("retval %ld, output: %ld, %ld, %ld, %ld\n", rv,
(unsigned long)ou_bytes[0], (unsigned long)ou_bytes[1],
(unsigned long)ou_bytes[2], (unsigned long)ou_bytes[3]);
}
}
iconv_close(context);
logmsg("Success!!!");
exit(EXIT_SUCCESS);
context_error:
iconv_close(context);
error:
logmsg("Error!!!");
exit(EXIT_FAILURE);
}
/* end of file */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment