BCS*_*BCS 897 .net c# arrays string type-conversion
我有一个byte[]从我碰巧知道包含UTF-8的文件加载的数组.在一些调试代码中,我需要将其转换为字符串.有没有一个班轮可以做到这一点?
在封面下它应该只是一个分配和一个memcopy,所以即使它没有实现,它应该是可能的.
Zan*_*oni 1410
string result = System.Text.Encoding.UTF8.GetString(byteArray);
Run Code Online (Sandbox Code Playgroud)
det*_*ale 309
这种转换至少有四种不同的方式.
编码的GetString
,但如果这些字节具有非ASCII字符,则无法获得原始字节.
BitConverter.ToString
输出是一个" - "分隔的字符串,但是没有.NET内置方法将字符串转换回字节数组.
Convert.ToBase64String
您可以使用使用简单地将输出字符串转换回字节数组Convert.FromBase64String.
注意:输出字符串可以包含"+","/"和"=".如果要在URL中使用该字符串,则需要对其进行显式编码.
HttpServerUtility.UrlTokenEncode
您可以使用,轻松地将输出字符串转换回字节数组HttpServerUtility.UrlTokenDecode.输出字符串已经是URL友好的!缺点是,System.Web如果您的项目不是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
Run Code Online (Sandbox Code Playgroud)
Nir*_*Nir 22
当您不知道编码时,从字节数组转换为字符串的一般解决方案:
static string BytesToStringConverted(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Erç*_*ğlu 13
定义:
public static string ConvertByteToString(this byte[] source)
{
return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}
Run Code Online (Sandbox Code Playgroud)
使用:
string result = input.ConvertByteToString();
Run Code Online (Sandbox Code Playgroud)
Ant*_*rdo 11
我在这篇文章中看到了一些答案,它可以被认为是完整的基础知识,因为我在 C# 编程中有多种方法可以解决相同的问题。唯一需要考虑的是纯 UTF-8和带有BOM的 UTF-8之间的区别。
上周,在我的工作中,我需要开发一项功能,输出带有 BOM 的 CSV 文件以及带有纯 UTF-8(无 BOM)的其他 CSV 文件。每种 CSV 文件编码类型都会被不同的非标准化 API 使用。一个 API 读取带 BOM 的 UTF-8,另一种 API 读取不带 BOM 的内容。我需要研究有关这个概念的参考文献,阅读“ UTF-8 和没有 BOM 的 UTF-8 之间有什么区别? ” Stack Overflow 问题,以及维基百科文章“字节顺序标记”来构建我的方法。
最后,我的两种 UTF-8 编码类型(带有 BOM 和纯)的 C# 编程需要与下面的示例类似:
// For UTF-8 with BOM, equals shared by Zanoni (at top)
string result = System.Text.Encoding.UTF8.GetString(byteArray);
//for Pure UTF-8 (without B.O.M.)
string result = (new UTF8Encoding(false)).GetString(byteArray);
Run Code Online (Sandbox Code Playgroud)
将a转换byte[]为a string似乎很简单,但任何类型的编码都可能会使输出字符串变得混乱.这个小功能正常工作,没有任何意外的结果:
private string ToString(byte[] bytes)
{
string response = string.Empty;
foreach (byte b in bytes)
response += (Char)b;
return response;
}
Run Code Online (Sandbox Code Playgroud)
使用(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;
}
}
Run Code Online (Sandbox Code Playgroud)
还有类UnicodeEncoding,使用起来非常简单:
ByteConverter = new UnicodeEncoding();
string stringDataForEncoding = "My Secret Data!";
byte[] dataEncoded = ByteConverter.GetBytes(stringDataForEncoding);
Console.WriteLine("Data after decoding: {0}", ByteConverter.GetString(dataEncoded));
Run Code Online (Sandbox Code Playgroud)
该类BitConverter可用于将 a 转换byte[]为string.
var convertedString = BitConverter.ToString(byteAttay);
Run Code Online (Sandbox Code Playgroud)
类的文档可以在MSDNBitConverter上找到。