温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C# string byte数组转换方法

发布时间:2021-07-16 10:29:10 来源:亿速云 阅读:577 作者:chen 栏目:编程语言

这篇文章主要讲解了“C# string byte数组转换方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C# string byte数组转换方法”吧!

C# string byte数组转换实现的过程是什么呢?C# string byte数组间的转换需要注意什么呢?C# string byte数组间转换所涉及的方法是什么呢?让我们来看看具体的内容:

C# string byte数组转换之string类型转成byte[]:

byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );

反过来,byte[]转成string:

string str = System.Text.Encoding.Default.GetString ( byteArray );

其它编码方式的,如System.Text.UTF8Encoding,System.Text.UnicodeEncoding class等;例如:

string类型转成ASCII byte[]:("01" 转成 byte[] = new byte[]{ 0x30, 0x31})

byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );

ASCII byte[] 转成string:(byte[] = new byte[]{ 0x30, 0x31} 转成 "01")

string str = System.Text.Encoding.ASCII.GetString ( byteArray );

有时候还有这样一些需求:

byte[] 转成原16进制格式的string,例如0xae00cf, 转换成 "ae00cf";new byte[]{ 0x30, 0x31}转成"3031":

public static string ToHexString ( byte[] bytes ) // 0xae00cf => "AE00CF "  {  string hexString = string.Empty;  if ( bytes != null )  {  StringBuilder strB = new StringBuilder ();   for ( int i = 0; i < bytes.Length; i++ )  {  strB.Append ( bytes[i].ToString ( "X2" ) );  }  hexString = strB.ToString ();  }  return hexString;  }

C# string byte数组转换之16进制格式的string 转成byte[]

例如, "ae00cf"转换成0xae00cf,长度缩减一半;"3031" 转成new byte[]{ 0x30, 0x31}:

public static byte[] GetBytes(string hexString, out int discarded)  {  discarded = 0;  string newString = "";  char c;  // remove all none A-F, 0-9, characters  for (int i=0; i<HEXSTRING.LENGTH; I++) SPAN  <>{  c = hexString[i];  if (IsHexDigit(c))  newString += c;  else discarded++;  }  // if odd number of characters, discard last character  if (newString.Length % 2 != 0)  {  discarded++;  newString = newString.Substring(0, newString.Length-1);  }   int byteLength = newString.Length / 2;  byte[] bytes = new byte[byteLength];  string hex;  int j = 0;  for (int i=0; i<BYTES.LENGTH; I++) SPAN  <>{  hex = new String(new Char[] {newString[j], newString[j+1]});  bytes[i] = HexToByte(hex);  j = j+2;  }  return bytes;  }

感谢各位的阅读,以上就是“C# string byte数组转换方法”的内容了,经过本文的学习后,相信大家对C# string byte数组转换方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI