The mbrtoc16() function is defined in <cuchar> header file.
mbrtoc16() prototype
size_t mbrtoc16( char16_t* pc16, const char* s, size_t n, mbstate_t* ps);
The mbrtoc16() function converts at most n multibyte character represented by s to its equivalent utf-16 character and stores it in the memory location pointed to by pc16.
If s represents a null pointer, the values of n and pc16 are ignored and the call to is equivalent to mbrtoc16(NULL, "", 1, ps).
If the resulting character produced is null, the conversion state *ps represents the initial shift state.
mbrtoc16() Parameters
- pc16: Pointer to the memory location to store the resulting 16 bit character.
- s: Pointer to the multibyte character to convert.
- n: Maximum number of bytes in s to convert.
- ps: A pointer to an mbstate_t object used when interpreting the multibyte string.
mbrtoc16() Return value
The mbrtoc16() function returns the first of the following value that matches the cases below:
- 0 if the converted character is a null character.
- the number of bytes (at most n) of the multibyte character that was successfully converted to 16 bit character.
- -3 if the next
char16_t
from a multi-char16_t character (e.g. a surrogate pair) has now been written to *pc16. No bytes are processed from the input in this case. - -2 if the next n bytes constitute an incomplete, but so far valid, multibyte character. In this case nothing is written to *pc16.
- -1 if encoding error occurs. In this case nothing is written to *pc16, errno is set to EILSEQ and the value of *ps is unspecified.
Example: How mbrtoc16() function works?
#include <cstdio>
#include <cstdlib>
#include <cuchar>
#include <iostream>
using namespace std;
int main(void)
{
char16_t pc16;
char s[] = "x" ;
mbstate_t ps{};
int length;
length = mbrtoc16(&pc16, s, MB_CUR_MAX, &ps);
if (length < 0)
{
perror("mbrtoc16() fails to convert");
exit(-1);
}
cout << "Multibyte string = " << s << endl;
cout << "Length = " << length << endl;
printf ("16-bit character = 0x%04hx\n", pc16);
return 0;
}
When you run the program, the output will be:
Multibyte string = x Lengt>h = 1 16-bit character = 0x0078