Creating a wchar to multibyte char function
The libc library I'm currently using is missing wctomb() so I开发者_JS百科'm looking to come up with a replacement implementation. What are some complexities I should beware of? Can I simply grab each byte in the wchar and stick them inside an char array?
You might want to pick up a copy of P.J. Plauger's book, "The Standard C Library" - it provides a basic implementation of wctomb()
along with a discussion of wide character support in general.
It depends in what encoding is the wchar
and what encoding do you expect in char
array. If they are the same (the encodings), then AFAIK yes, you can do it byte by byte, but beware of endiannes.
You can easily assign each wchar to a char if the wchar is <= 127 so only 7bit are used. As long as you check this and create an error if it isn't given you are save and can do so.
Thats because the first 7 bit og the unicode character (no matter if 8, 16 or 32 bit) is identical with the first 7 bit of ASCII.
If you really want to write a converter you need to know a lot of character tables and so on.
There is a full featured unicode library call ICU which was inspired by IBM. Its very powerful and big. But it might help if nothing helps.
If you are absolutely sure that your program will only ever handle ASCII data (which is really a terrible thing to assume, but it may be necessary), then you can just take the lower-order byte of each wchar_t
and stuff it into a char
. But if you ever have to handle any kind of Unicode data, then you're going to be stuck implementing UTF-8, which is a massive undertaking best left to experts.
精彩评论