c32rtomb() function in C/C++?

In C programming, the c32rtomb() function is used to convert a 32-bit wide character (char32_t) to its corresponding multibyte character representation. This function is defined in the uchar.h header file and is part of the C11 standard for Unicode support.

Syntax

size_t c32rtomb(char *s, char32_t c32, mbstate_t *ps);

Parameters

  • s − Pointer to a character array where the multibyte character will be stored
  • c32 − The 32-bit wide character to convert
  • ps − Pointer to an mbstate_t object that holds the conversion state

Return Value

The function returns the number of bytes written to the character array on success. If an encoding error occurs, it returns (size_t)-1 and sets errno to EILSEQ.

Note: To compile and run this example, ensure your compiler supports C11 standard and Unicode functions. Use gcc -std=c11 or a compatible compiler.

Example: Converting 32-bit Characters to Multibyte

This example demonstrates how to convert a 32-bit Unicode string to multibyte characters −

#include <stdio.h>
#include <uchar.h>
#include <string.h>
#include <locale.h>

int main() {
    setlocale(LC_ALL, "");  /* Set locale for proper encoding */
    
    const char32_t myStr[] = U"Hello World";
    char dest[10];  /* Buffer for multibyte character */
    mbstate_t state = {0};  /* Initialize conversion state */
    size_t length;
    int j = 0;
    
    printf("Converting 32-bit string to multibyte:\n");
    
    while (myStr[j] != U'\0') {
        memset(dest, 0, sizeof(dest));  /* Clear buffer */
        length = c32rtomb(dest, myStr[j], &state);
        
        if (length == (size_t)-1) {
            printf("Encoding error occurred\n");
            break;
        }
        
        if (length == 0) {
            break;  /* Null character encountered */
        }
        
        /* Print the converted multibyte character */
        for (size_t i = 0; i < length; i++) {
            putchar(dest[i]);
        }
        
        j++;
    }
    
    printf("\n");
    return 0;
}
Converting 32-bit string to multibyte:
Hello World

Key Points

  • The function processes one 32-bit character at a time and converts it to its multibyte representation
  • The mbstate_t object maintains the conversion state between function calls
  • Always check the return value for encoding errors
  • Setting the locale may be necessary for proper character encoding

Conclusion

The c32rtomb() function provides a standard way to convert 32-bit Unicode characters to multibyte sequences in C. It's essential for applications that need to handle Unicode text and convert between different character representations safely.

Updated on: 2026-03-15T10:53:40+05:30

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements