在JavaSCRIPT中可以用encode和unencode函數再用上正則表達式可以將比如"中" 轉化成"中"表示.
在C#中我們可以用Rexgex.Repalce()這個方法來處理,實現的代碼如下:
頁面的代碼如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
public partial class UnicodeToGB2312 : System.Web.UI.Page
...{
protected void Page_Load(object sender, EventArgs e)
...{
}
protected void btnConvert_Click(object sender, EventArgs e)
...{
string result = txtContent.Text;
if (btnConvert.Text == "解碼")
...{
btnConvert.Text = "編碼";
result = UnEncode(result);
txtContent.Text = result;
}
else
...{
btnConvert.Text = "解碼";
result = Encode(result);
txtContent.Text = result;
}
}
protected string Encode(string inputString)
...{
MatchEvaluator matchEvaluator = new MatchEvaluator(EncodeFindSubString); //初始化一個委托,該委托用於處理Regex.Repalce中每次匹配的match對象
string result = System.Text.RegularExpressions.Regex.Replace(inputString, @"[^\u0000-\u00FF]", matchEvaluator);
return result;
}
protected string UnEncode(string inputString)
{
MatchEvaluator matchEvaluator = new MatchEvaluator(UnEncodeFindSubString);
string result = System.Text.RegularExpressions.Regex.Replace(inputString, @"&#x([0-9a-fA-F]{4});", matchEvaluator);
return result;
}
protected string EncodeFindSubString(Match match) //編碼的時候委托處理函數
{
byte[] bytes = Encoding.Unicode.GetBytes(match.Value);
string result = "";
for (int i = bytes.Length - 1; i >= 0; i--)
{
result += ToHexString(bytes[i]);
}
result = "&#x" + result + ";";
return result;
}
protected string UnEncodeFindSubString(Match match) //解碼的時候委托處理函數
{
string result = match.Groups[1].Value;
byte[] bytes = new byte[2]; //4E 2D
bytes[1] = byte.Parse(result.Substring(0,2),System.Globalization.NumberStyles.AllowHexSpecifIEr);
bytes[0] = byte.Parse(result.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifIEr);
result = result.Replace(result, Encoding.Unicode.GetString(bytes));
return result;
}
protected string ToHexString(byte a) //返回一個16進制表示的數
{
string result = a.ToString("X");
if (result.Length == 2)
{
return result;
}
else
{
return "0" + result; //如果就一位比如"7"的16進制返回的是"7"而我們需要 "07"
}
}
}
<%...@ Page Language="C#" AutoEventWireup="true" CodeFile="UnicodeToGB2312.ASPx.cs" Inherits="UnicodeToGB2312" validateRequest=false %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xHtml1-transitional.dtd">
<html XMLns="http://www.w3.org/1999/xHtml" >
<head runat="server">
<title>Unicode<->GB2312轉換</title>
</head>
<body>
<form id="form1" runat="server">
<div >
<asp:TextBox ID="txtContent" runat="server" Height="507px" TextMode="MultiLine" Width="814px"></ASP:TextBox>
<br />
<br />
<ASP:Button ID="btnConvert" runat="server" Text="解碼" OnClick="btnConvert_Click" Height="24px" Width="59px" /></div>
</form>
</body>
</Html>