Multibytetowidechar and widechartomultibyte usage

Source: Internet
Author: User
This is the multi-byte string we need to convert:
Char stext [20] = {"Multi-byte string! OK! "};

We need to know how many array spaces are required for converted wide characters. although in this mileage, we can directly define an array of 20*2 Characters in width, and in fact it will run very easily and happily. however, if there are more multi-byte strings and tens of thousands or even tens of thousands of strings, we will find that more and more memory will be wasted. therefore, it is definitely not a good idea to use the double number of multi-byte characters as the declaration of the bottom mark of the wide character array.
Fortunately, we can determine the array space we need.
We only need to set the fourth parameter of multibytetowidechar () to-1 to return the number of spaces in the required short character array:
DWORD dwnum = multibytetowidechar (cp_acp, 0, stext,-1, null, 0 );

Next, we only need to allocate the response array space:
Wchar_t * pwtext;
Pwtext = new wchar_t [dwnum];
If (! Pwtext)
{
Delete [] pwtext;
}

Next, we can start to convert it. Here we use the conversion to ASCII code as an example:
Multibytetowidechar (cp_acp, 0, stext,-1, pwtext, dwsize );

Finally, remember to release the occupied memory after use:
Delete [] pwtext;

Similarly, the Code for converting a wide character into a multi-byte character is as follows:
Wchar_t wtext [20] = {L "wide character conversion instance! OK! "};
DWORD dwnum = widechartomultibyte (cp_oemcp, null, lpcwszstr,-1, null, 0, null, false );
Char * pstext;
Pstext = new char [dwnum];
If (! Pstext)
{
Delete [] pstext;
}
Widechartomultibyte (cp_oemcp, null, lpcwszstr,-1, pstext, dwnum, null, false );
Delete [] pstext;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.