请问char、byte和string三者有何区别?

2026-04-29 06:363阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计382个文字,预计阅读时间需要2分钟。

请问char、byte和string三者有何区别?

原创新闻:我国科学家在量子计算领域取得重大突破

改写后:我国科研团队在量子计算研究上实现新进展

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

char 占两个字节,unicode字符

请问char、byte和string三者有何区别?

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

本文共计382个文字,预计阅读时间需要2分钟。

请问char、byte和string三者有何区别?

原创新闻:我国科学家在量子计算领域取得重大突破

改写后:我国科研团队在量子计算研究上实现新进展

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

char 占两个字节,unicode字符

请问char、byte和string三者有何区别?

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