C# byte 和 char 转化

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



c# 使用的是unicode字符集,应该和为ascii相互转换 只能转换到字符的unicode编码,或者由unicode编码转换为字符

转换方法如一楼所写
字符变数字
char a='a';
int ua=(int)a;//字符变整数
a=(char)ua;//整数变回字符
--------------------- 
  • 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; 
    }

 

char[]转化为byte[]:

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

// 这样转换,一个2字节的char,只转换为1个byte。

 

byte[]转化为char[]:

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

 

  • byte转换为char:

    public static char byteToChar(byte[] b) { 
        char c = (char) (((b[0] & 0xFF) << 8) | (b[1] & 0xFF)); 
        return c; 
    }

原文地址:https://www.cnblogs.com/nimorl/p/9836071.html