VS GBK encoding and UTF-8 encoding conversion

Source: Internet
Author: User

#include <Windows.h>


Note: multibyte includes GBK and UTF-8

int Gbk2utf8 (char *szgbk,char *szutf8,int Len)

{

Converts multibyte GBK (CP_ACP or ANSI) to wide characters first UTF-16

The number of memory characters required after the conversion is obtained

int n = MultiByteToWideChar (cp_acp,0,szgbk,-1,null,0);

Number of characters multiplied by sizeof (WCHAR) to get the number of bytes

WCHAR *str1 = new Wchar[sizeof (WCHAR) * n];

Transformation

MultiByteToWideChar (CP_ACP,//multibyte code page

0,//additional signs, related to phonetic transcription

SZGBK,//input GBK string

-1,//input string length, 1 means internal calculation by function

STR1,//output

N//output required memory allocated

);


Convert wide character (UTF-16) to multibyte (UTF-8)

n = WideCharToMultiByte (Cp_utf8, 0, STR1,-1, NULL, 0, NULL, NULL);

if (n > Len)

{

DELETE[]STR1;

return-1;

}

WideCharToMultiByte (Cp_utf8, 0, STR1,-1, SzUtf8, n, null, NULL);

DELETE[]STR1;

STR1 = NULL;


return 0;

}



UTF-8 GBK

int UTF82GBK (char *szutf8,char *szgbk,int Len)

{

int n = MultiByteToWideChar (Cp_utf8, 0, SzUtf8,-1, NULL, 0);

WCHAR * WSZGBK = new Wchar[sizeof (WCHAR) * n];

memset (WSZGBK, 0, sizeof (WCHAR) * n);

MultiByteToWideChar (Cp_utf8, 0,szutf8,-1, WSZGBK, N);


n = WideCharToMultiByte (CP_ACP, 0, WSZGBK,-1, NULL, 0, NULL, NULL);

if (n > Len)

{

DELETE[]WSZGBK;

return-1;

}


WideCharToMultiByte (cp_acp,0, WSZGBK,-1, SZGBK, n, null, NULL);


DELETE[]WSZGBK;

WSZGBK = NULL;


return 0;

}


VS GBK encoding and UTF-8 encoding conversion

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.