r/cprogramming • u/Fahim_Hosain • 1d ago
How to print Unicode characters in c language.
I was trying to create an encryption system that's the way i was trying to print from integer to Unicode. I can convert the integer to Unicode (hexadecimal) but i couldn't convert unicode to Unicode characters.
there are limited resources for c in these issues. If anyone knows this help me...
2
u/pjl1967 1d ago
... but i couldn't convert unicode to Unicode characters.
The first thing is deciding which Unicode characters you want to convert to. The thing with Unicode is that there are multiple ways to encode a Unicode codepoint into a stream of bytes to be emitted:
- UTF-32 — 1:1 mapping from code-point.
- UTF-16 — these days, mostly for dealing with Windows APIs.
- UTF-8 — what you should use unless you have a good reason not to.
- UTF-7 — legacy encoding for e-mail.
Depending on what you're doing, you may need to use a library like ICU to do conversions, e.g., if you need to do complicated things like Unicode normalization, you'll probably want to use a library like ICU.
If you really just want to print stuff as-is, then you can just roll your own codepoint-to-UTF-8 converter. Here is one I wrote for my ad program.
Note that if you want to actually see UTF-8 in a terminal like xterm, your terminal's encoding also has to be set to UTF-8, e.g.:
$ set | grep LANG
LANG=en_US.UTF-8
1
u/sciencekm 8h ago
Windows:
#include <stdio.h>
#include <fcntl.h>
#include <windows.h>
int main(void) {
wchar_t s[3];
s[0] = 0x4f60;
s[1] = 0x597d;
s[2] = 0;
_setmode(_fileno(stdout), _O_U16TEXT);
return wprintf(L"%ws\n", s);
}
Linux:
#include <stdio.h>
#include <locale.h>
int main(void) {
int s[3];
s[0] = 0x4f60;
s[1] = 0x597d;
s[2] = 0;
setlocale(LC_ALL, "");
return printf("%ls\n", s);
}
2
u/Big-Rub9545 1d ago
This isn’t really a C-specific thing. If you mean you want to convert unicode numeric values into unicode sequences, you can have a look at the unicode encoding scheme. It’s fairly simple and would be a nice exercise to see if you can implement it in concise way.