// Mimics the functionality of strlen() in c/c++
// Needed because niether StringBuilder or Encoding.*.GetString() handle \0 well
static int StringLength(byte[] buffer, int startIndex = 0)
{
int strlen = 0;
while
(
(startIndex + strlen + 1) < buffer.Length // Make sure incrementing won't break any bounds
&& buffer[startIndex + strlen] != 0 // The typical null terimation check
)
{
++strlen;
}
return strlen;
}
// This is messy, but I haven't found a built-in way in c# that guarentees null termination
public static string ParseBytes(byte[] buffer, out int strlen, int startIndex = 0)
{
strlen = StringLength(buffer, startIndex);
byte[] c_str = new byte[strlen];
Array.Copy(buffer, startIndex, c_str, 0, strlen);
return Encoding.UTF8.GetString(c_str);
}
string result = System.Text.Encoding.UTF8.GetString(byteArray);
2
使用 (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;
}
}
13 回答
用于将从文件读取的字节数组
byteArrFilename
转换为纯粹的ascii C样式的零终止字符串的Linq one-liner将是这样的:用于读取旧存档格式的文件索引表之类的内容 .我使用
'?'
作为默认字符,用于此处不纯的ascii,但当然可以更改 . 如果你想确定你可以检测它,只需使用'\0'
,因为启动时TakeWhile
确保以这种方式构建的字符串不可能包含来自输入源的'\0'
值 .当您不知道编码时,从字节数组转换为字符串的一般解决方案:
据我所知,没有给出的答案保证使用空终止的正确行为 . 在有人向我展示不同之前,我使用以下方法编写了自己的静态类来处理它:
startIndex
的原因是在我正在研究的示例中,我需要将byte[]
解析为空终止字符串数组 . 在简单的情况下可以安全地忽略它使用
(byte)b.ToString("x2")
,输出b4b5dfe475e58b67
试试这个:
hier是你不必费心编码的结果 . 我在我的网络类中使用它并将二进制对象作为字符串发送 .
这种转换至少有四种不同的方式 .
Encoding's GetString
,但如果这些字节具有非ASCII字符,您将无法获得原始字节 .
BitConverter.ToString
输出是一个"-"分隔的字符串,但是没有.NET内置方法将字符串转换回字节数组 .
Convert.ToBase64String
您可以使用
Convert.FromBase64String
轻松地将输出字符串转换回字节数组 .注意:输出字符串可以包含'+','/'和'=' . 如果要在URL中使用该字符串,则需要对其进行显式编码 .
HttpServerUtility.UrlTokenEncode
您可以使用
HttpServerUtility.UrlTokenDecode
轻松地将输出字符串转换回字节数组 . 输出字符串已经是URL友好的!缺点是如果您的项目不是Web项目,它需要System.Web
汇编 .一个完整的例子:
Definition:
Using:
BitConverter
类可用于将byte[]
转换为string
.BitConverter
类的文档可以在MSDN上获取将
byte[]
转换为string
似乎很简单,但任何类型的编码都可能会使输出字符串变得混乱 . 这个小功能正常工作,没有任何意外的结果:或者:
还有类UnicodeEncoding,使用起来非常简单: