本文介绍了如何在C#中将字符串转换为字节数组,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我通过以下方法将Byte数组转换为String:
我的Byte数组是myArray,我从另一个地方获取它,
所以,我不知道用来获取它的代码页
Hi guys,
I convert an array of Byte to String by this method:
my array of Byte is myArray that i get it form another place,
So, i do not know the code page that used to get it
StringBuilder StringPlus = new StringBuilder();
for (int i = 0; i < myArray.Length; i++)
{
StringPlus.Append(myArray[i].ToString());
}
我想从String转换为Byte,而结果数组等于我的第一个
重要说明:
我不知道用于获取原始数组 myArray
的代码页
我想要的是:
从字节数组转换为字符串,然后再次转换为字节数组
不是从字符串到字节数组,而是从字符串
I want to convert from String to Byte whereas the resulted Array equal to my first
Important note:
I do not know the Without knowing the code page that used to get the original array myArray
i want that:
convert from Byte array to string then to Byte array again
Not from string to Byte array then to string
推荐答案
string myString = //... some string
System.Text.Encoding encoding = System.Text.Encoding.UTF8; //or some other, but prefer some UTF is Unicode is used
byte[] bytes = encoding.GetBytes(myString);
//next lines are written in response to a follow-up questions:
myString = new string(encoding.GetChars(bytes));
byte[] bytes = encoding.GetBytes(myString);
myString = new string(encoding.GetChars(bytes));
byte[] bytes = encoding.GetBytes(myString);
//how many times shall I repeat it to show there is a round-trip? :-)
//string to byte array
string theMessage = "This is a message!";
byte[] bytes = Encoding.ASCII.GetBytes(theMessage);
//byte array to string
string theMessage2 = Encoding.ASCII.GetString(bytes);
Console.WriteLine(theMessage2);
//string to byte array
String str = "Hello";
byte[] btarr = ASCIIEncoding.ASCII.GetBytes(str);
//byte array to string
StringBuilder StringPlus = new StringBuilder();
for (int i = 0; i < btarr.Length; i++)
{
StringPlus.Append(Convert.ToChar(btarr[i]));
}
这篇关于如何在C#中将字符串转换为字节数组,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!