using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace Example37

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Shown(object sender, EventArgs e)

        {

            this.Text = "汉字与区位码的转换";

        }

        private void button1_Click(object sender, EventArgs e)

        {

            if (textBox1.Text != string.Empty)

            {

                try

                {

                    textBox2.Text = getCode(textBox1.Text);

                }

                catch (IndexOutOfRangeException ex)

                {

                    MessageBox.Show(ex.Message + "请输入正确的汉字", "错误");

                }

            }

        }

        

        // 获得 汉字 区位码 方法 

        public string getCode(string Chinese)

        {

            string P_str_Code = "";

            byte[] P_bt_Array = new byte[2];        //定义字节数组 存放汉字 

            P_bt_Array = Encoding.Default.GetBytes(Chinese);    //为字节数组 赋值 

            int front = (short)(P_bt_Array[0] - '\0');          //将字节数组第一位转换为int类型

            int back = (short)(P_bt_Array[1] - '\0');           //将字节数组第二位转换为int类型

            P_str_Code = (front - 160).ToString() + (back - 160).ToString();  //计算区位码

            return P_str_Code;

        }

    }

}

posted on 2011-10-18 21:50  C#_初学者  阅读(499)  评论(0编辑  收藏  举报