sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

C#中byte数组与string类型之间的转换
原文链接:https://blog.csdn.net/weixin_44359158/article/details/116457477

string类型转换为byte[]:

string str = "Test";
byte[] bytTemp = System.Text.Encoding.Default.GetBytes(str);
  • 1
  • 2

byte[]转换为string

string strTemp = System.BitConverter.ToString(bytTemp);
  • 1

但是得到的结果为54-65-73-74,这里需要进行转换
转换代码:

string[] strSplit = strTemp.Split('-');   
byte[] bytTemp2 = new byte[strSplit.Length];
for(int i = 0; i < strSplit.Length; i++)
{
	bytTemp2[i] = byte.Parse(strSplit[i],System.Globalization.NumberStyles.AllowHexSpecifier);
}
string strResult = System.Text.Encoding.Default.GetString(bytTemp2);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

可以看到strResult = “Test”

posted on 2023-04-12 19:28  sunny123456  阅读(348)  评论(0编辑  收藏  举报