如何将byte []转换为该文本格式?

Iva*_*nov 1 c# formatting text

我可以说我不知道​​我在寻求帮助,因为我不知道格式,但我有一张照片.

我有一个byte []数组,如何将其转换为下面的格式(右图)?

替代文字http://img512.imageshack.us/img512/3548/48667724.jpg

它不是简单的ascii.

Dan*_*ant 6

这听起来像你想要一个字节数组,并将其转换为文本(用" ."s 替换某个范围之外的字符)

static public string ConvertFromBytes(byte[] input)
{
    StringBuilder output = new StringBuilder(input.Length);

    foreach (byte b in input)
    {
        // Printable chars are from 0x20 (space) to 0x7E (~)
        if (b >= 0x20 && b <= 0x7E)
        {
            output.Append((char)b);
        }
        else
        {
            // This isn't a text char, so use a placehold char instead
            output.Append(".");
        }
    }

    return output.ToString();
}
Run Code Online (Sandbox Code Playgroud)

或者作为LINQy扩展方法(在静态扩展类中):

static public string ToPrintableString(this byte[] bytes)
{
    return Encoding.ASCII.GetString
           (
              bytes.Select(x => x < 0x20 || x > 0x7E ? (byte)'.' : x)
                   .ToArray()
           );
}
Run Code Online (Sandbox Code Playgroud)

(你可以这样称呼string printable = byteArray.ToPrintableString();)


Guf*_*ffa 5

用于b.ToString("x2")将字节值格式化为两个字符的十六进制字符串.

对于ASCII显示,检查该值是否对应于常规可打印字符,如果是,则将其转换为:

if (b >= 32 && b <= 127) {
   c = (char)b;
} else {
   c = '.';
}
Run Code Online (Sandbox Code Playgroud)

或更短:

c = b >= 32 && b <= 127 ? (char)b : '.';
Run Code Online (Sandbox Code Playgroud)

要在数组上执行此操作:

StringBuilder builder = new StringBuilder();
foreach (b in theArray) {
   builder.Append(b >= 32 && b <= 127 ? (char)b : '.');
}
string result = builder.ToString();
Run Code Online (Sandbox Code Playgroud)