mbrtoc16() in C/C++ with Examples

CC++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of std::mbrtoc16() function in C++ STL.

What is std::mbrtoc16()?

std::mbrtoc16() function is an inbuilt function in C++ STL, which is defined in <cuchar> header file. This function is used to convert a narrow multibyte character to UTF-16-character representation.

If the associated character pointer is not null, and all other parameters are also accepted then it will convert the corresponding 16-bit character.


size_t mbrtoc16( char16_t* pc16, char* str, size_t n, mbstate_t* ps);


The function accepts following parameter(s) −

  • pc16 − This is the pointer to the location we want the output to be stored.
  • str − Character string which is used as the input.
  • n − It is the number of bytes that are to be checked.
  • ps − It is the pointer to the state object when we are interpreting the multibyte string.

Return value

This function return values differ as per the following condition −

  • 0 − The function will return zero when the character in str which has to be converted is NULL.
  • 1…n − The number of bytes of multibyte character which are converted from the character string *str.
  • -3 − If there is a surrogate pair means, the char16_t is from a multi-char16_t. No bytes are to be made from the input.
  • -2 − We will get -2 when next n bytes incomplete but so far is valid multibyte character.
  • -1 − We get -1 when we face an encoding error, nothing is written to *pc16.


 Live Demo

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <uchar.h>
#include <wchar.h>
using namespace std;
int main(void){
   char16_t hold;
   char str[] = "I";
   mbstate_t arr{};
   int len;
   // initializing the function
   len = mbrtoc16(&hold, str, MB_CUR_MAX, &arr);
   if (len < 0) {
      perror("conversion failed");
   cout << "String is: " << str << endl;
   cout << "Length is: " << len << endl;
   printf("16-bit character = 0g%02hd\n", hold);


String is: I
Length is: 1
16-bit character = 0g73
Published on 17-Apr-2020 09:51:15