Skip to content

Instantly share code, notes, and snippets.

@opsJson
Created May 5, 2024 01:56
Show Gist options
  • Save opsJson/9e54cbea6351799baed2e5e470ce95be to your computer and use it in GitHub Desktop.
Save opsJson/9e54cbea6351799baed2e5e470ce95be to your computer and use it in GitHub Desktop.
Widechar to Multibyte and Multibyte to Widechar in Windows
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <windows.h>
wchar_t *atow(char *str) {
wchar_t *result;
int length;
if (str == NULL) return NULL;
length = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
result = malloc((length + 1) * sizeof(wchar_t));
if (result == NULL) return NULL;
MultiByteToWideChar(CP_UTF8, 0, str, -1, result, length);
result[length] = L'\0';
return result;
}
char *wtoa(wchar_t *wstr) {
char *result;
size_t size;
if (wstr == NULL) return NULL;
size = WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, wstr, -1, NULL, 0, NULL, NULL);
if (size <= 0) return NULL;
result = malloc(size + 1);
if (result == NULL) return NULL;
if (WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, wstr, -1, result, size, NULL, NULL) <= 0) {
free(result);
return NULL;
}
result[size] = '\0';
return result;
}
int main(void) {
setlocale(LC_ALL, "");
char *str = wtoa(L"Não é Âncora");
wchar_t *wstr = atow(str);
wprintf(L"(%ls)\n", wstr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment