• char[] byte[] string


    C#  byte 和 char 可以认为是等价的。但是在文本显示的时候有差异。 

    char 占两个字节,unicode字符 

    1、内存转换:

    • char转化为byte:
    public static byte[] charToByte(char c) { 
            byte[] b = new byte[2]; 
            b[0] = (byte) ((c & 0xFF00) >> 8); 
            b[1] = (byte) (c & 0xFF); 
            return b; 
        }
    • byte转换为char:
     public static char byteToChar(byte[] b) { 
            char c = (char) (((b[0] & 0xFF) << 8) | (b[1] & 0xFF)); 
            return c; 
        }

    2、字符串转换

    char[]转化为byte[]:

    char[] cChar=new char[5]{a,b,c,d,e};   
    byte[] byteData=Encoding.Default.GetBytes(cChar);  

    byte[]转化为char[]:

    byte[] byteData=new byte[5]{0x01,0x02,0x03,0x04,0x05};   
    char[] cChar=Encoding.ASCII.GetChars(byteData);  

    string类型转成byte[]:

    byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );

    byte[]转成string:

    string str = System.Text.Encoding.Default.GetString ( byteArray );

    string类型转成ASCII byte[]:

    byte[] = new byte[]{ 0x30,0x31};    // "01" 
    byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );

    ASCIIbyte[]转成string:

    byte[] = new byte[]{ 0x30, 0x31};  //  "01"
    string str = System.Text.Encoding.ASCII.GetString ( byteArray );

    string 转换成 Char[]
      

    string ss = "我爱你,中国";
    char[] cc = ss.ToCharArray();

    Char[] 转换成string
      

    string s = new string(cc);

    byte[] 与 string 之间的装换
      

    byte[] bb = Encoding.UTF8.GetBytes(ss);
    string s = Encoding.UTF8.GetString(bb);
  • 相关阅读:
    1009 Product of Polynomials (25分)
    VS code 调试C++
    1065 A+B and C (64bit) (20分)
    UML与数据库应用系统
    语句(switch,异常,NDEBUG,assert)
    1046 Shortest Distance (20分)
    1042 Shuffling Machine (20分)
    模块和包
    闭包&装饰器
    迭代器、生成器
  • 原文地址:https://www.cnblogs.com/jshchg/p/11656388.html
Copyright © 2020-2023  润新知