C#下字符串与字节数组之间的相互转换

来源:互联网 发布:通用视频监控软件 编辑:程序博客网 时间:2024/04/30 21:20

 

      在某些应用中,我们经常要把字符串编码后再拆解成一个一个的字节(字节数组)进行存储。在需要的时候再把这一个一个的字节拼接成字符串进行还原。这就需要依照某种统一的原则对字符串序列进行编码以及对相应的字节数组进行解码。对于简单的西文应用,如数字和英文字母,由于其ASCII码都为一个字节,字节数固定,可以统一由ASCII码来编码和还原,其过程比较简单。但是对于中西文混合的情况,不同的字符对于某种编码规则(如UTF-8),其对应的字节数也可能不同。为了节约存储空间,尽可能采用字节数较少的编码方式。如UTF-8比UTF-16编码方式要精简,而UTF-16又要比UTF-32编码方式精简。下面以UTF-8为例,简单介绍C#程序下的字符串拆解与还原过程。

           

            //编码字符串

            string info="1.23AB清华大学CD9YZK%*&#";

            Encoding targetEncoding;

            byte[] encodedChars;         

            int codePage = 65001;   // UTF-8

 

            System.Text.Encoding encoding = System.Text.Encoding.UTF8;

 

          //   Gets   the   encoding   for   the   specified   code   page.  

            targetEncoding = Encoding.GetEncoding(codePage);

 

            //   Gets   the   byte   representation   of   the   specified   string.  

            encodedChars = targetEncoding.GetBytes(info);

 

            int length = encodedChars.Length;

            byte[] result = new byte[length + 1];

            for (int i = 0; i < length; i++) // 数组后移一个字节,第一个字节腾出来放长度(字节数)

            {

                result[i + 1] = encodedChars[i];

            }

            result[0] = (Byte)length;

 

            // 将编码后的数组进行存储

 

            // ……

 

            // 提取编码后的数组进行还原

 

            //还原字符串

            length = result[0];

            for (int i = 0; i < length; i++)

            {

                encodedChars[i] = result[i + 1];

            }

            info = encoding.GetString(encodedChars);           

            MessageBox.Show("还原后的字符串:" + info);

 

-----------------------------------------------------------------

北京贝斯曼信息技术有限公司 技术部 奉华成

(www.besmann.com)


北京无线点菜系统 餐饮管理系统

原创粉丝点击