码迷,mamicode.com
首页 > 其他好文 > 详细

char[] byte[] string

时间:2019-10-11 20:14:30      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:unicode   getch   字符串转换   code   gets   sci   get   new   pre   

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

 

char[] byte[] string

标签:unicode   getch   字符串转换   code   gets   sci   get   new   pre   

原文地址:https://www.cnblogs.com/jshchg/p/11656388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!