這幾個月作手機短信的項目,碰到了很多字元編碼的問題,真頭痛。經過多番資料的搜尋、親手嘗試和高人的指點,現在好像沒那麼迷惘了。現作了一些總結跟大家分享(有誤之處請指點)
首先應該把位元組數組看成是String的載體。
dot Net使用的字元串String是Unicode編碼的;它也是以Unicode編碼的形式顯示字元串。
以下是用自己語言對幾個常用函數的說明:
(自己總結的,反正看不明MSDN)
bytes=System.Text.Encoding.Unicode.GetBytes(str)
作用:把str的載體作Unicode->Unicode的編碼轉換--也就是沒有對載體作任何的轉換。因些使用此函數可以得代表該String載體的位元組數組。
str=System.Text.Encoding.Unicode.GetString(bytes)
作用:對位元組數組作Unicode->Unicode的編碼轉換--即沒有轉換,把經過轉換後的位元組數組作為str的載體。
bytes=System.Text.Encoding.Utf8.GetBytes(str)
作用:把str的載體作Utf8->Unicode的編碼轉換。傳回的是經過轉換後的字元數組
str=System.Text.Encoding.Utf8.GetString(bytes)
作用:對位元組數組作Gb2312->Unicode的編碼轉換,把經過轉換後的位元組數組作為str的載體。
bytes=System.Text.Encoding.GetEncoding("GB2312").GetBytes(str)
作用:把str的載體作Gb2312->Unicode的編碼轉換。傳回的是經過轉換後的字元數組
str=System.Text.Encoding.GetEncoding("GB2312").GetString(bytes)
作用:對位元組數組作Gb2312->Unicode的編碼轉換,把經過轉換後的位元組數組作為str的載體。
如此類推
bytes=System.Text.Encoding.GetEncoding("XXX").GetBytes(str)
作用:把str的載體作XXX->Unicode的編碼轉換。傳回的是經過轉換後的字元數組
str=System.Text.Encoding.GetEncoding("XXX").GetString(bytes)
作用:對位元組數組作XXX->Unicode的編碼轉換,把經過轉換後的位元組數組作為str的載體。
這裡是我收集的一些有關字元編碼的資料:http://61.145.116.154/bm/
還有:
http://www.unicode.org/charts/unihan.html
根據Unicode編碼查其對應字元的字形、Utf8、漢字區位碼等
http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/GB/GB2312.TXT Unicode與Gb2312的對照表
http://www.sun.com/developers/gadc/technicalpublications/articles/mabiao.txt
Unicode與Gbk對照表
// string a= "\xb4\x41\x23";
// byte[] b= new byte[3];
// b[0]=(byte)a[0];
// b[1]=(byte)a[1];
// b[2]=(byte)a[2];
//
// string a= "\xb4\x41\x23";
// byte[] b= Encoding.ASCII.GetBytes(a);
//
// byte[] = System.Text.Encoding.ASCII.GetBytes(string)
// 相反:string -->byte[]
// string = System.Text.Encoding.Asscii.GetString(byte[]);
//
// string strTemp = "我abc";
// for(int i = 0; i < strTemp.Length; i ++)
// {
// string sTemp = strTemp.Substring(i, 1);
// int iLen = System.Text.Encoding.Default.GetByteCount(sTemp);
// if(iLen == 2)
// {
// //雙位元組
// }
// else
// {
// //單位元組
// }
// }
//
// char ch="a";
// if((int)ch>255)
// {
// //雙位元組
// }
// else
// {
// //單位元組
// }
// CString strText;//中間字元串
// strText.Format("%d",byLenth);//10進制->中間字元串
// sscanf(strText,"%x",&temp);//中間字元串->16進制資料
// char *pData = new char [10] ;
// CString strData2 ;
// // int d = 32 ;
// sprintf(pData,"%02x",byLenth) ;
// strData2 = pData ;
// delete []pData ;
char 是一個字元,如果用來表示數值的話,能表示-128--127之間
byte 是無符号 char 如果用來表示數值的話,能表示 0-255之間