Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

mbrtoc8 — C23 Unicode-conversion function

`mbrtoc8(pc8, s, n, ps)` from C23 `<uchar.h>` converts the next execution multibyte character into successive UTF-8 `char8_t` code units; in C23, `char8_t` is the same type as `unsigned char`. It examines at most `n` bytes, while `mbstate_t` retains a partial character and pending units.

Version: C23

Syntax

size_t mbrtoc8(char8_t * restrict pc8, const char * restrict s, size_t n, mbstate_t * restrict ps);

mbrtoc8(pc8, s, n, ps) from C23 <uchar.h> converts the next execution multibyte character into successive UTF-8 char8_t code units; in C23, char8_t is the same type as unsigned char. It examines at most n bytes, while mbstate_t retains a partial character and pending units.

The example uses explicit state and really calls mbrtoc8 for the single-byte string "!". The function returns 1, stores UTF-8 unit 0x21, and output 1 21 checks both effects. The code requires a C23 library implementation that provides this newly standardized function.

0 denotes the null character and initial state, -2 incomplete input, -1 an EILSEQ error with unspecified state, and -3 storage of a further UTF-8 unit from the previous character without consuming new bytes. Do not advance s after -3; after -2, provide remaining bytes with the same ps. When s == NULL, the call is exactly equivalent to mbrtoc8(NULL, "", 1, ps); pc8 and n are ignored. This is the specified empty-string call in the current conversion state, not a promise of an unconditional reset. With non-null s, pc8 == NULL suppresses only the store; explicit ps avoids internal state that is not required to be race-free.

Examples

#include <stdio.h>
#include <uchar.h>
int main(void){mbstate_t state={0};char8_t unit=0;size_t count=mbrtoc8(&unit,"!",1,&state);printf("%zu %02X\n",count,(unsigned)unit);return 0;}

Result

1 21

The example uses explicit state and really calls `mbrtoc8` for the single-byte string `"!"`. The function returns `1`, stores UTF-8 unit `0x21`, and output `1 21` checks both effects. The code requires a C23 library implementation that provides this newly standardized function.

Sources