Programming

C++에서 UTF8, Unicode, Ansi 문자열 변환..

steloflute 2016. 2. 8. 23:26

참고: http://linsoo.co.kr/m/post/entry/C%EC%97%90%EC%84%9C-UTF8-Unicode-Ansi-%EB%AC%B8%EC%9E%90%EC%97%B4-%EB%B3%80%ED%99%98


그런데, 윗글에는 오류가 있다. lstrlen을 strlen으로 바꾸면 정상 작동한다.


Ansi를 UTF-8로 변환

char* ANSIToUTF8(const char * pszCode)
{
	int		nLength, nLength2;
	BSTR	bstrCode; 
	char*	pszUTFCode = NULL;

	nLength = MultiByteToWideChar(CP_ACP, 0, pszCode, strlen(pszCode), NULL, NULL); 
	bstrCode = SysAllocStringLen(NULL, nLength); 
	MultiByteToWideChar(CP_ACP, 0, pszCode, strlen(pszCode), bstrCode, nLength);

	nLength2 = WideCharToMultiByte(CP_UTF8, 0, bstrCode, -1, pszUTFCode, 0, NULL, NULL); 
	pszUTFCode = (char*)malloc(nLength2+1); 
	WideCharToMultiByte(CP_UTF8, 0, bstrCode, -1, pszUTFCode, nLength2, NULL, NULL); 

	return pszUTFCode;
}


UTF-8을 ANSI로 변환 

char* UTF8ToANSI(const char *pszCode)
{ BSTR bstrWide; char* pszAnsi; int nLength; nLength = MultiByteToWideChar(CP_UTF8, 0, pszCode, strlen(pszCode) + 1, NULL, NULL); bstrWide = SysAllocStringLen(NULL, nLength); MultiByteToWideChar(CP_UTF8, 0, pszCode, strlen(pszCode) + 1, bstrWide, nLength); nLength = WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, NULL, 0, NULL, NULL); pszAnsi = new char[nLength]; WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, pszAnsi, nLength, NULL, NULL); SysFreeString(bstrWide); return pszAnsi; }


'Programming' 카테고리의 다른 글

Go 언어의 장단점  (0) 2016.03.09
C/C++ macros  (0) 2016.02.21
C++에서 UTF-8 사용  (0) 2016.02.06
자바 디자인 패턴 5 - Singleton  (0) 2016.01.21
(Go) slice literal  (0) 2016.01.20