用C++编写一个内部以urf-8方式解码的String对象, 实现std::string或者java.lang.String 的基本的操作和功
我java很熟,c++很少用,连class怎么构造都搞不太明白。。。哪位大神教教我。。。。就算不编这个代码,教我一些utf-8和ASCII转换的基本原理,以及c++编写c...
我java很熟,c++很少用,连class怎么构造都搞不太明白。。。哪位大神教教我。。。。就算不编这个代码,教我一些utf-8和ASCII转换的基本原理,以及c++编写class的基本方法。。。。
展开
1个回答
展开全部
utf-8,是用变码去编码宽字符
// 转换UNICODE到UTF8
bool CUTF8::Unicode_UTF8( char *pBuffer, int nSize )
{
int nLen = 0;
int nToBuffer = 0;
wchar_t *pUnicode = (wchar_t*)pBuffer;
if( nSize % 2 != 0 )
return false;
nLen = nSize / 2;
ClearBuffer();
m_pBuffer = new char[nSize * 3];
if( NULL == m_pBuffer )
return false;
for( int nLoop = 0; nLoop < nLen; nLoop++ )
{
if( pUnicode[ nLoop ] <= 0x7F )
{
m_pBuffer[ nToBuffer ] = pUnicode[ nLoop ] & 0x7F;
nToBuffer++;
}
else if( pUnicode[ nLoop ] > 0x7F && pUnicode[nLoop]<=0x7FF )
{
m_pBuffer[ nToBuffer + 1 ] = ( pUnicode[ nLoop ] & 0x3F ) | 0x80;
m_pBuffer[ nToBuffer ] = ( pUnicode[ nLoop ]>>6 & 0x1F ) | 0xC0;
nToBuffer += 2;
}
else if( pUnicode[nLoop] > 0x7FF && pUnicode[nLoop]<=0xFFFF )
{
m_pBuffer[ nToBuffer + 2 ] = ( pUnicode[ nLoop ] & 0x3F ) | 0x80;
m_pBuffer[ nToBuffer + 1 ] = ( pUnicode[ nLoop ]>>6 & 0x3F ) | 0x80;
m_pBuffer[ nToBuffer ] = ( pUnicode[ nLoop ]>>12 & 0xF ) | 0xE0;
nToBuffer += 3;
}
}
m_nSize = nToBuffer;
if( m_nSize>nSize * 3 )
return false;
return true;
}
// 转换UNICODE到UTF8
bool CUTF8::Unicode_UTF8( char *pBuffer, int nSize )
{
int nLen = 0;
int nToBuffer = 0;
wchar_t *pUnicode = (wchar_t*)pBuffer;
if( nSize % 2 != 0 )
return false;
nLen = nSize / 2;
ClearBuffer();
m_pBuffer = new char[nSize * 3];
if( NULL == m_pBuffer )
return false;
for( int nLoop = 0; nLoop < nLen; nLoop++ )
{
if( pUnicode[ nLoop ] <= 0x7F )
{
m_pBuffer[ nToBuffer ] = pUnicode[ nLoop ] & 0x7F;
nToBuffer++;
}
else if( pUnicode[ nLoop ] > 0x7F && pUnicode[nLoop]<=0x7FF )
{
m_pBuffer[ nToBuffer + 1 ] = ( pUnicode[ nLoop ] & 0x3F ) | 0x80;
m_pBuffer[ nToBuffer ] = ( pUnicode[ nLoop ]>>6 & 0x1F ) | 0xC0;
nToBuffer += 2;
}
else if( pUnicode[nLoop] > 0x7FF && pUnicode[nLoop]<=0xFFFF )
{
m_pBuffer[ nToBuffer + 2 ] = ( pUnicode[ nLoop ] & 0x3F ) | 0x80;
m_pBuffer[ nToBuffer + 1 ] = ( pUnicode[ nLoop ]>>6 & 0x3F ) | 0x80;
m_pBuffer[ nToBuffer ] = ( pUnicode[ nLoop ]>>12 & 0xF ) | 0xE0;
nToBuffer += 3;
}
}
m_nSize = nToBuffer;
if( m_nSize>nSize * 3 )
return false;
return true;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询