UTF-8与本地字符转换

本文介绍了一个用于本地编码与UTF8编码相互转换的封装类CCodingConv。该类提供了两个静态方法:ConvertStringToUTF8用于从本地编码转换到UTF8编码;ConvertUTF8ToString则用于从UTF8编码转换回本地编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CodingConv.h

/**
 * \file CodingConv.h
 * \brief 编码格式转换接口定义文件
 */
#pragma once

/**
 * \class CCodingConv CodingConv.h
 * \brief 本地编码类型与UTF8编码类型转换封装类,用于sqlite中的编码类型转换
 * \date 2010-6-8 9:31
 */
class CCodingConv  
{
public:
    /**
     * \brief 将本地编码类型转换为UTF8编码类型
     * \param[in] strIn 本地编码类型的字符串
     * \param[out] strOutUTF8MB 转换后的UTF8编码格式的字符串
     * \return 转换后的字符串长度
     * \attention 本地函数为strOutUTF8MB申请的内存要在外部释放
     */
    static size_t ConvertStringToUTF8( LPCTSTR strIn, char *& strOutUTF8MB );

    /**
     * \brief 将UTF8编码类型转换为本地编码类型
     * \param[in] strInUTF8MB UTF8编码类型的字符串
     * \param[in] len strInUTF8MB字符串的长度
     * \param[out] strOut 转换后的本地编码格式的字符串
     * \return NONE
     */
    static void ConvertUTF8ToString( char * strInUTF8MB, size_t len, LPTSTR & strOut );
};

CodingConv.cpp

/**
 * \file CodingConv.cpp
 * \brief 编码格式转换接口实现文件
 */
#include "stdafx.h"
#include <Windows.h>
#include <tchar.h>
#include "CodingConv.h"

void CCodingConv::ConvertUTF8ToString( char * strInUTF8MB, size_t len, LPTSTR & strOut )
{
    strOut=new TCHAR[len];
    strOut[0]=0;

#ifdef UNICODE
    MultiByteToWideChar(CP_UTF8, 0, strInUTF8MB, (int)len, strOut, (int)len);
#else
    WCHAR * wChar=new WCHAR[len];
    wChar[0]=0;
    MultiByteToWideChar(CP_UTF8, 0, strInUTF8MB, (int)len, wChar, (int)len);
    WideCharToMultiByte(CP_ACP, 0, wChar, (int)len, strOut, (int)len, 0, 0);
    delete [] wChar;
#endif
}

size_t CCodingConv::ConvertStringToUTF8( LPCTSTR strIn, char *& strOutUTF8MB )
{
    size_t len=_tcslen(strIn);

#ifdef UNICODE
    int iRequiredSize=WideCharToMultiByte(CP_UTF8, 0, strIn, -1, 0, 0, 0, 0);

    strOutUTF8MB=new char[iRequiredSize];
    strOutUTF8MB[0]=0;

    WideCharToMultiByte(CP_UTF8, 0, strIn, -1, strOutUTF8MB, iRequiredSize, 0, 0);
#else
    WCHAR * wChar=new WCHAR[len+1];
    wChar[0]=0;
    MultiByteToWideChar(CP_ACP, 0, strIn, (int)len+1, wChar, (int)len+1);
    int iRequiredSize=WideCharToMultiByte(CP_UTF8, 0, wChar, (int)len+1, 0, 0, 0, 0);
    strOutUTF8MB=new char[iRequiredSize];
    strOutUTF8MB[0]=0;
    WideCharToMultiByte(CP_UTF8, 0, wChar, (int)len+1, strOutUTF8MB, iRequiredSize, 0, 0);
    delete [] wChar;
#endif

    return iRequiredSize;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值