CodeBlanks Logo Icon CodeBlanks

Multibyte conversion

Learn multibyte and wide character conversion.

mbstowcs and wcstombs

mbstowcs converts a multibyte string to a wide character array; wcstombs does the reverse. Both are in <stdlib.h>.

mbstowcs(NULL, s, 0) only counts the resulting wide characters; it does not allocate memory. mbstowcs(wbuf, s, n) writes to wbuf. For an ASCII string the byte count and wide character count are equal: both are 7 for "Merhaba". You must call setlocale(LC_ALL, "") or "C" before conversion; otherwise the behavior is undefined.

ASCII conversion

For the ASCII string "Merhaba", strlen returns 7 and mbstowcs(NULL, s, 0) also returns 7. One byte per character maps to one wide character.

If the string were "çağ", strlen would return 5 (two letters are two bytes each) and mbstowcs would return 3. In this lesson we stick to ASCII; we begin with setlocale(LC_ALL, "C") so the output is deterministic. After conversion we print the counts with printf instead of wprintf.

Practice Byte and wide character count

First call setlocale(LC_ALL, "C");. Declare const char *s = "Merhaba";. Compute size_t mb = strlen(s); and size_t wcs = mbstowcs(NULL, s, 0);. Print printf("mb: %zu\n", mb); and printf("wcs: %zu\n", wcs);.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>

// Call setlocale to 'C'
// For "Merhaba" print strlen and mbstowcs counts

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>

int main(void) {
    setlocale(LC_ALL, "C");
    const char *s = "Merhaba";
    size_t mb = strlen(s);
    size_t wcs = mbstowcs(NULL, s, 0);
    printf("mb: %zu\n", mb);
    printf("wcs: %zu\n", wcs);
    return 0;
}

Expected output

mb: 7
wcs: 7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does mbstowcs(NULL, s, 0) do?

  • Returns an error
  • Allocates memory
  • Copies the string
  • Counts wide characters Correct answer

Explanation: When the third parameter is 0, it only counts.

2 Match conversion functions

Term Meaning
mbstowcs Multibyte→wide
wcstombs Wide→multibyte
setlocale Sets locale
strlen Counts bytes

3 mbstowcs call

Question
size_t n = mbstowcs(NULL, s, ____);
Answer
size_t n = mbstowcs(NULL, s, 0);

Explanation: A third parameter of 0 is the counting mode.

All lessons in Advanced