Conversion between GBK and utf8-my study
Conversion between GBK and utf8 ByCnangelOn October 8, 2012 10 AM | No Comments
The conversion between GBK and UTF-8, many beginners will be confused.
In general, GBK and UTF-8 is the encoding method of the text, the corresponding internal code is not the same, so the conversion of GBK and UTF-8 needs to map the internal code one by one, and then convert.
Libiconv is generally used for general system projects, but libiconv is a little huge for embedded or mobile operating systems.
Here we provide functions such as GBK and utf8 conversion, full-width and case-sensitivity conversion, and hope to help mobile phone developers, especially those who develop on IOS.
Strnormalize. h
Strnormalize. c
For details about how to use simplified and Traditional Chinese conversion, seeCode:
# include "strnormalize. H "
# include
# include
# include
int main (INT argc, char ** argv)
{< br> str_normalize_init ();
unsigned Options = sno_to_lower | sno_to_half;
If (argc> 1) Options = atoi (argv [1]);
char * buffer = (char *) malloc (65536 );
memset (buffer, 0, 65536);
while (fgets (buffer, 65536, stdin)
{< br> str_normalize_utf8 (buffer, options );
printf ("% s", buffer);
}< br> free (buffer);
return 0;
}
The UTF-8 and GBK conversion methods are as follows:
# Include "strnormalize. H"
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <stdint. h>
Int main (INT argc, char ** argv)
{
Str_normalize_init ();
Const char * utf8 = "I Am a UTF-8 character! ";
Const char * GBK = "�� GBK �� ";
Uint32_t utf8_len = strlen (utf8 );
Uint32_t gbk_len = strlen (utf8 );
Uint32_t utf8buffer_len = utf8_len * 3 + 1;
Uint32_t gbkbuffer_len = gbk_len * 2 + 1;
Char * utf8buffer = (char *) malloc (utf8buffer_len );
Char * gbkbuffer = (char *) malloc (gbkbuffer_len );
Memset (utf8buffer, 0, utf8buffer_len );
Memset (gbkbuffer, 0, gbkbuffer_len );
Utf8_to_gbk (utf8, utf8_len, & gbkbuffer, & gbkbuffer_len );
Gbk_to_utf8 (GBK, gbk_len, & utf8buffer, & utf8buffer_len );
Printf ("utf8: % S <=> % d \ t gbkbuffer: % S <=> % d \ n", utf8, utf8_len, gbkbuffer, gbkbuffer_len );
Printf ("GBK: % S <=> % d \ t utf8buffer: % S <=> % d \ n", GBK, gbk_len, utf8buffer, utf8buffer_len );
Free (utf8buffer );
Free (gbkbuffer );
Return 0;
}
Categories :
Tags :