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);

相关文章

文章浏览阅读6.2k次,点赞2次,收藏3次。C#数学运算表达式解...
文章浏览阅读5.2k次,点赞6次,收藏7次。程序要做到用户配置...
文章浏览阅读9k次。错误信息检测到 ContextSwitchDeadlock M...
文章浏览阅读2w次,点赞10次,收藏9次。我发生错误时的环境:...
文章浏览阅读9.8k次。C# 二进制字节流查找函数IndexOf ...
文章浏览阅读2.5w次,点赞3次,收藏9次。c#DataGridView数据...