使用System.Convert.ToString將字符串轉換成utf16進制編碼

 

我們在編寫某些特殊的字符串處理程序的時候,需要獲得字符的16進制編碼,這個在vb中一般使用asc函數來進行,但是在c#中就沒有那麼簡單。前一陣,爲了將url中的漢字轉換成utf編碼的,我發現可以用System.Convert.ToString這函數來完成這樣的操作。

這個函數就是將url中的漢字轉換成utf編碼:

public string Str2Hex(string strInput)

{

UTF8Encoding utf8=new UTF8Encoding();

string unicodeString=strInput;//strinput就是需要轉換的漢字字符串

string str="";

Byte[] encodedBytes=utf8.GetBytes(unicodeString);//轉換成數組

for (int i=0;i<(encodedBytes.Length);i++ )

{

str=str+"%25";//因爲ReportingService中的特殊要求,需要在每個漢字前增加一個“%25,即%本身的編碼”

str=str+System.Convert.ToString(encodedBytes[i],16);//轉換成16進制的編碼。

}

return str;

}

 

//這個函數和上面的大同小異,只是直接在漢字中間加上%而不是它的編碼

public string StrToHex(string strInput)

{

UTF8Encoding utf8=new UTF8Encoding();

string unicodeString=strInput;

string str="";

Byte[] encodedBytes=utf8.GetBytes(unicodeString);

for (int i=0;i<(encodedBytes.Length);i++ )

{

str=str+"%";

str=str+System.Convert.ToString(encodedBytes[i],16);

}

return str;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章