我有一个byte[]数组,它是从一个我所知道的包含UTF-8的文件中加载的。 在一些调试代码中,我需要将其转换为字符串。 是否有一个班轮可以做到这一点?
在幕后 ,它应该只是一个分配和一个内存复制 ,因此即使未实现它也应该是可能的。
#1楼
string result = System.Text.Encoding.UTF8.GetString(byteArray);
#2楼
至少有四种不同的方式可以完成此转换。
编码的GetString
,但如果原始字节具有非ASCII字符,则将无法找回原始字节。
BitConverter.ToString
输出是一个以“-”分隔的字符串,但是没有.NET内置方法将字符串转换回字节数组。
Convert.ToBase64String
您可以使用Convert.FromBase64String轻松将输出字符串转换回字节数组。
注意:输出字符串可以包含“ +”,“ /”和“ =”。 如果要在URL中使用字符串,则需要对其进行显式编码。
HttpServerUtility.UrlTokenEncode
您可以使用HttpServerUtility.UrlTokenDecode轻松地将输出字符串转换回字节数组。 输出字符串已经是URL友好的了! 缺点是,如果您的项目不是Web项目,则需要System.Web程序集。
一个完整的例子:
byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters
string s1 = Encoding.UTF8.GetString(bytes); // ���
byte[] decBytes1 = Encoding.UTF8.GetBytes(s1); // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results
string s2 = BitConverter.ToString(bytes); // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
decBytes2[i] = Convert.ToByte(tempAry[i], 16);
// decBytes2 same as bytes
string s3 = Convert.ToBase64String(bytes); // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes
string s4 = HttpServerUtility.UrlTokenEncode(bytes); // gsjqFw2
byte[] decBytes4 = HttpServerUtility.UrlTokenDecode(s4);
// decBytes4 same as bytes
#3楼
定义:
public static string ConvertByteToString(this byte[] source)
{
return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}
使用方法:
string result = input.ConvertByteToString();
#4楼
使用(byte)b.ToString("x2") ,输出b4b5dfe475e58b67
public static class Ext {
public static string ToHexString(this byte[] hex)
{
if (hex == null) return null;
if (hex.Length == 0) return string.Empty;
var s = new StringBuilder();
foreach (byte b in hex) {
s.Append(b.ToString("x2"));
}
return s.ToString();
}
public static byte[] ToHexBytes(this string hex)
{
if (hex == null) return null;
if (hex.Length == 0) return new byte[0];
int l = hex.Length / 2;
var b = new byte[l];
for (int i = 0; i < l; ++i) {
b[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return b;
}
public static bool EqualsTo(this byte[] bytes, byte[] bytesToCompare)
{
if (bytes == null && bytesToCompare == null) return true; // ?
if (bytes == null || bytesToCompare == null) return false;
if (object.ReferenceEquals(bytes, bytesToCompare)) return true;
if (bytes.Length != bytesToCompare.Length) return false;
for (int i = 0; i < bytes.Length; ++i) {
if (bytes[i] != bytesToCompare[i]) return false;
}
return true;
}
}
#5楼
将byte[]转换为string似乎很简单,但是任何类型的编码都可能使输出字符串混乱。 这个小功能可以正常工作而不会产生任何意外结果:
private string ToString(byte[] bytes)
{
string response = string.Empty;
foreach (byte b in bytes)
response += (Char)b;
return response;
}