zoukankan      html  css  js  c++  java
  • C#字节数组转换成字符串

     

      如果还想从 System.String 类中找到方法进行字符串和字节数组之间的转换,恐怕你会失望了。为了进行这样的转换,我们不得不借助另一个类:System.Text.Encoding。该类提供了 bye[] GetBytes(string) 方法将字符串转换成字节数组,还提供了 string GetString(byte[]) 方法将C#字节数组转换成字符串。

    如下字符串与字节数组互换的例子:

    byte[] msg = Encoding.Unicode.GetBytes(textBox1.Text);
                this.label1.Text = Encoding.Unicode.GetString(msg);

     

      System.Text.Encoding 类似乎没有可用的构造函数,但我们可以找到几个默认的 Encoding,即 Encoding.Default(获取系统的当前 ANSI 代码页的编码)、Encoding.ASCII(获取 7 位 ASCII 字符集的编码)、Encoding.Unicode(获取采用 Little-Endian 字节顺序的 Unicode 格式的编码)、Encoding.UTF7(获取 UTF-7 格式的编码)、Encoding.UTF8(获取 UTF-8 格式的编码) 等。这里主要说说 Encoding.Default 和 Encoding.Unicode 用于转换的区别。

     

      在字符串转换到字节数组的过程中,Encoding.Default 会将每个单字节字符,如半角英文,而把每个双字节字符,如汉字。而 Encoding.Unicode 则会将它们都转换成两个字节。我们可以通过下列简单的了解一下转换的方法,以及使用 Encoding.Default 和 Encodeing.Unicode 的区别:

     

    private void TestStringBytes() {  

    string s = "C#语言";  

    byte[] b1 = System.Text.Encoding.Default.GetBytes(s);  

    byte[] b2 = System.Text.Encoding.Unicode.GetBytes(s);  

    string t1 = "", t2 = "";  

    foreach (byte b in b1) {  

    t1 += b.ToString("") + " ";  

    }  

    foreach (byte b in b2) {  

    t2 += b.ToString("") + " ";  

    }  

    this.textBox1.Text = "";  

    this.textBox1.AppendText("b1.Length = " + b1.Length + "\n");  

    this.textBox1.AppendText(t1 + "\n");  

    this.textBox1.AppendText("b2.Length = " + b2.Length + "\n");  

    this.textBox1.AppendText(t2 + "\n");  

    } 

     

      运行结果如下,不说详述,相信大家已经明白了。

     

    b1.Length = 6 

    67 35 211 239 209 212  

    b2.Length = 8 

    67 0 35 0 237 139 0 138  

     

      将C#字节数组转换成字符串,使用 Encoding 类的 string GetString(byte[]) 或 string GetString(byte[], int, int) 方法,具体使用何种 Encoding 还是由编码决定。在 TestStringBytes() 函数中添加如下语句作为实例:

     

    byte[] bs = {97, 98, 99, 100, 101, 102};  

    string ss = System.Text.Encoding.ASCII.GetString(bs);  

    this.textBox1.AppendText("The string is: " + ss + "\n"); 

     

      运行结果为:The string is: abcdef

    时间的步伐有三种:未来姗姗来迟,现在像箭一样飞逝,过去永远静立不动.务请珍惜
  • 相关阅读:
    Mysql的联合索引-最左匹配的隐藏规则
    C#读取word文档内容
    安装完office后 在组件服务里DCOM配置中找不到的解决方案
    .NET Web应用程序发布后无法读取Word文档的解决方法
    web程序读取word报异常:COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件失败,原因是出现以下错误: 80070005 拒绝访问。最新解决方案
    C# 读取txt格式文件内容
    idea 社区版开发 springbook及问题
    Visualvm jvisualvm1.8详情使用
    VSCODE 打造完美java开发环境(新)
    如何将sdk的jar包安装到本地maven库中
  • 原文地址:https://www.cnblogs.com/Asa-Zhu/p/2761137.html
Copyright © 2011-2022 走看看