Csharp/C#教程:C#中Byte[]和String之间转换的方法分享

本文给大家介绍如何在Byte[]和String之间进行转换?

比特(b):比特只有01,1代表有脉冲,0代表无脉冲。它是计算机物理内存保存的最基本单元。

字节(B):8个比特,0—255的整数表示

编码:字符必须编码后才能被计算机处理。早期计算机使用7为AscII编码,为了处理汉字设计了中文简体GB2312和big5

字符串与字节数组之间的转换,事实上是现实世界的信息和数字世界信息之间的转换,势必涉及到某种编码方式,不同的编码方式将导致不同的转换结果。C#中常使用System.Text.Encoding来管理常用的编码。下面直接上代码:

usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceByteToString { classProgram { staticvoidMain(string[]args) { stringstr="鞠哥真帅!"; //使用UTF编码。。。 Byte[]utf8=StrToByte(str,Encoding.UTF8); //估计C#当时设计时没有中文简体,这是后来中国搞的? Byte[]gb2312=StrToByte(str,Encoding.GetEncoding("GB2312")); Console.WriteLine("这是UTF8(鞠哥真帅),长度是:{0}",utf8.Length); foreach(variteminutf8) { Console.Write(item); } Console.WriteLine("nn这是gb2312(鞠哥真帅),长度是:{0}",gb2312.Length); foreach(varitemingb2312) { Console.Write(item); } //用utf8编码的字节数组转换为str stringutf8Str=ByteToStr(utf8,Encoding.UTF8); stringgb2312Str=ByteToStr(gb2312,Encoding.GetEncoding("GB2312")); Console.WriteLine("nnutf8:{0}",utf8Str); Console.WriteLine("gb2312:{0}",gb2312Str); Console.ReadKey(); } //C#通常使用System.Text.Encoding编码 //字符串转数组 staticByte[]StrToByte(stringstr,Encodingencoding) { returnencoding.GetBytes(str); } //数组转换字符串 staticStringByteToStr(Byte[]bt,Encodingencoding) { returnencoding.GetString(bt); } } }

上述就是C#学习教程:C#中Byte[]和String之间转换的方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/907493.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐