//解码
void __stdcall Utf8Decode( char* str, int maxSize )
{
wchar_t* tempBuf;
int len = strlen( str );
if ( len < 2 )
return;
tempBuf = ( wchar_t* )alloca(( len+1 )*sizeof( wchar_t ));
{
wchar_t* d = tempBuf;
BYTE* s = ( BYTE* )str;
while( *s )
{
if (( *s & 0x80 ) == 0 )
{ *d++ = *s++;
continue;
}
if (( s[0] & 0xE0 ) == 0xE0 && ( s[1] & 0xC0 ) == 0x80 && ( s[2] & 0xC0 ) == 0x80 )
{
*d++ = (( WORD )( s[0] & 0x0F) << 12 ) + ( WORD )(( s[1] & 0x3F ) << 6 ) + ( WORD )( s[2] & 0x3F );
s += 3;
continue;
}
if (( s[0] & 0xE0 ) == 0xC0 && ( s[1] & 0xC0 ) == 0x80 )
{
*d++ = ( WORD )(( s[0] & 0x1F ) << 6 ) + ( WORD )( s[1] & 0x3F );
s += 2;
continue;
}
*d++ = *s++;
}
*d = 0;
}
if ( maxSize == 0 )
maxSize = len;
WideCharToMultiByte( CP_ACP, 0, tempBuf, -1, str, maxSize, NULL, NULL );
}
//编码
char* __stdcall Utf8Encode( const char* src )
{
wchar_t* tempBuf;
int len = strlen( src );
char* result = ( char* )malloc( len*3 + 1 );
if ( result == NULL )
return NULL;
tempBuf = ( wchar_t* )alloca(( len+1 )*sizeof( wchar_t ));
MultiByteToWideChar( CP_ACP, 0, src, -1, tempBuf, len );
tempBuf[ len ] = 0;
{
wchar_t* s = tempBuf;
BYTE* d = ( BYTE* )result;
while( *s )
{
int U = *s++;
if ( U < 0x80 )
{
*d++ = ( BYTE )U;
}
else if ( U < 0x800 )
{
*d++ = 0xC0 + (( U >> 6 ) & 0x3F );
*d++ = 0x80 + ( U & 0x003F );
}
else
{
*d++ = 0xE0 + ( U >> 12 );
*d++ = 0x80 + (( U >> 6 ) & 0x3F );
*d++ = 0x80 + ( U & 0x3F );
} }
*d = 0;
}
return result;
}