This is my third article about getting started

mbstowcs()

size_t mbstowcs(schar_t *pwcs, const char *str, size_t n)
Copy the code

Parameters that

  • PWDS — Points to an array of wchar_t elements long enough to store a wide string of maximum character length.
  • STR – the multi-byte character string to be converted.
  • N — The maximum number of characters that can be converted.

Return instructions

  • Returns the array that is converted to the parameter PWCS.

This function converts multi-byte characters to wide characters

Example

#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <wchar.h>
 
int main(void)
{
         
	strcpy(utf8_str, "12345");
	int strlen = 10;
	size_t len = strlen(utf8_str) + 1;
	wchar_t *wstr = malloc(len * sizeof(wchar_t));

	if(! wstr) {return -1;
	}
	len = mbstowcs(wstr, utf8_str, len);
	wstr[len] = 0;
	free(wstr);
	return ret;
}
Copy the code

wcstombs()

Convert wide characters to multi-byte strings

size_t wcstombs(char *mbstr, const wchar_t *wcstr, size_t count);
Copy the code

Parameters that

  • MBSTR — Points to an array of char elements long enough to store a string of maximum character length.
  • STR – wide character string to be converted.
  • N — The maximum number of characters that can be converted.

Return instructions

  • Returns the array that is converted to the argument MBSTR.

Example

#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <wchar.h>
 
int main(void)
{
    Object str, newstr;
	const size_t len = wcstombs(NULL, str->value.wstring, 0) + 1;

	String_Realloc(newstr, len);
	wcstombs(newstr->value.string, str->value.wstring, len);

}
Copy the code

Usage scenarios

Win:

1. Convert Unicode to ANSI using MultiByteToWideChar. 2. Convert ANSI to Unicode using WideCharToMultiByte.Copy the code

Linux:

From wide character to multi-character:

   size_t wcstombs(char *mbstr, const wchar_t *wcstr, size_t count );
Copy the code

Multi-character width characters:

   size_t mbstowcs(wchar_t *wcstr, const char *mbstr, size_t count );
Copy the code

Note that wide-byte and multi-byte characters are implemented differently on different platforms. For example, the wchar_t type is implemented in Unicode, which is UTF-16 on Windows and UTF-32 on Linux.

There are many ways to realize multi-byte, such as UTF-8 and ACSII

Therefore, if you want to convert to the encoding you want to convert, you need to call the setlocale() function before calling to set the encoding and specify the multi-byte encoding type.