Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

c8rtomb — C23 library function

`c8rtomb(s, c8, ps)` converts a `char8_t` unit encoded as UTF-8 to the current `LC_CTYPE` multibyte representation, stores at most `MB_CUR_MAX` bytes, and returns the number stored including shift sequences.

Version: C23

Syntax

size_t c8rtomb(char * restrict s, char8_t c8, mbstate_t * restrict ps);

c8rtomb(s, c8, ps) converts a char8_t unit encoded as UTF-8 to the current LC_CTYPE multibyte representation, stores at most MB_CUR_MAX bytes, and returns the number stored including shift sequences.

Use an explicit mbstate_t while converting a stream. The example passes u8'A', receives the single-byte character A, and uses mbsinit to confirm that the state remains initial.

Because the input is UTF-8, a multibyte character can require several char8_t units; earlier calls then store nothing and return 0. A null s performs the equivalent null-character conversion into an internal buffer and restores the initial state. An encoding error returns (size_t)-1, sets errno = EILSEQ, and leaves the state unspecified; a null ps selects internal state for which the implementation need not avoid data races.

Examples

#include <limits.h>
#include <stdio.h>
#include <uchar.h>
#include <wchar.h>

int main(void) {
    mbstate_t state = {0};
    char output[MB_LEN_MAX];
    size_t count = c8rtomb(output, u8'A', &state);
    if (count == (size_t)-1) return 1;
    printf("%zu %c %d\n", count, output[0], mbsinit(&state));
    return 0;
}

Result

1 A 1

Use an explicit `mbstate_t` while converting a stream. The example passes `u8'A'`, receives the single-byte character `A`, and uses `mbsinit` to confirm that the state remains initial.

Sources