zoukankan      html  css  js  c++  java
  • String类型和Byte以及Byte数组之间的转换

    老鸟跳过. 只是简单介绍了一下如何利用UnicodeEncoding实现String类型和Byte以及Byte数组之间的转换. 实例代码取自MSDN.

    首先理解一个概念:

          编码是一个将一组 Unicode 字符转换为一个字节序列的过程。解码是将一个编码字节序列转换为一组 Unicode 字符的过程。

     

    废话不说, 放出代码.

    代码
    using System;
    using System.Text;

    class UnicodeEncodingExample {
    public static void Main() {
    // 实例化一个UnicodeEncoding对象,用于转换.
    UnicodeEncoding unicode = new UnicodeEncoding();

    // 创建一个包含Unicode码的字符串.
    String unicodeString =
    "This Unicode string contains two characters " +
    "with codes outside the traditional ASCII code range, " +
    "Pi (\u03a0) and Sigma (\u03a3).";
    Console.WriteLine(
    "Original string:");
    Console.WriteLine(unicodeString);

    // 把String类型转换成Byte[]数组
    Byte[] encodedBytes = unicode.GetBytes(unicodeString);
    Console.WriteLine();
    Console.WriteLine(
    "Encoded bytes:");
    foreach (Byte b in encodedBytes) {
    Console.Write(
    "[{0}]", b);
    }
    Console.WriteLine();

    // 把Byte[]数组转换成String
    String decodedString = unicode.GetString(encodedBytes);
    Console.WriteLine();
    Console.WriteLine(
    "Decoded bytes:");
    Console.WriteLine(decodedString);
    }
    }


    我们用到了UnicodeEncoding这个类.这个类还提供了比如Char[]类型和Byte[]之间的转换.很方便.

    如果是把String类型转换成Byte类型,而不是Byte数组.可以使用Byte.Parse()方法.需要注意的是: String必须符合Format条件.一般只可以包含空白,以及一个0~255之间的数字.

    Sample:

    代码
    //可以转换
    string str1 = " 255 ";
    Console.WriteLine(Byte.Parse(str1));

    //报错,FormatException
    string str2 = "a string";
    Byte.Parse(str2);

    //报错,OverflowException
    string str3 = "256";
    Console.WriteLine(Byte.Parse(str3));

    详细: http://msdn.microsoft.com/zh-cn/library/k0s9b1y3(VS.95).aspx

            http://msdn.microsoft.com/zh-cn/library/system.text.unicodeencoding.aspx

  • 相关阅读:
    Python os 方法指南
    网站后台500错误分析
    HTML中的meta标签常用属性及其作用总结
    Python线程理论
    python之struct详解
    python之路——初识面向对象
    configparser和hashlib模块
    logging模块
    re模块
    pickle,shelve,json模块
  • 原文地址:https://www.cnblogs.com/anyanran/p/1795849.html
Copyright © 2011-2022 走看看