Question

I can say I don't know what I'm asking for help,because I don't know the format,but I've got a picture.

I have a byte[] array ,how do I convert it to that format below(in right)?

alt text http://img512.imageshack.us/img512/3548/48667724.jpg

Its not plain ascii.

Was it helpful?

Solution

Use b.ToString("x2") to format a byte value into a two character hexadecimal string.

For the ASCII display, check if the value corresponds to a regular printable character and convert it if it is:

if (b >= 32 && b <= 127) {
   c = (char)b;
} else {
   c = '.';
}

Or shorter:

c = b >= 32 && b <= 127 ? (char)b : '.';

To do it on an array:

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

OTHER TIPS

It sounds like you'd like to take an array of bytes, and convert it to text (replacing characters outside of a certain range with "."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();
}

or as a LINQy extension method (inside a static extension class):

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

(You could call that like string printable = byteArray.ToPrintableString();)

This could be any number of encodings... try this test test script to see which of them print out:

Bl8s

Here is the script:

byte[] b = new byte[] {0x42, 0x6C, 0x38, 0x73 };
foreach (EncodingInfo ei in Encoding.GetEncodings())
{
     Console.WriteLine("{0} - {1}", ei.GetEncoding().GetString(b), ei.Name);
}

[edit 2018:] Re-wrote the function from scratch to make the code much more efficient and fix some other problems. You can now also optionally specify a starting offset and number of bytes (starting from there) to display.


If you want the whole memory display, including the offset number, and left and right displays, you can do it like this: (32-byte width)

/// <summary> Returns a String where the specified bytes are formatted in a
/// 3-section debugger-style aligned memory display, 32-bytes per line </summary>
public static unsafe String MemoryDisplay(byte[] mem, int i_start = 0, int c = -1)
{
    if (mem == null)
        throw new ArgumentNullException();
    if (i_start < 0)
        throw new IndexOutOfRangeException();
    if (c == -1)
        c = mem.Length - i_start;
    else if (c < 0)
        throw new ArgumentException();
    if (c == 0)
        return String.Empty;

    char* pch = stackalloc Char[32];       // for building right side at the same time
    var sb = new StringBuilder((c / 32 + 1) * 140);            // exact pre-allocation

    c += i_start;
    for (int i = i_start & ~0x1F; i < c;)
    {
        sb.Append(i.ToString("x8"));
        sb.Append(' ');

        do
        {
            if (i < i_start || i >= c)          // non-requested area, or past the end
            {
                sb.Append("   ");   
                pch[i & 0x1F] = ' ';
            }
            else
            {
                var b = mem[i];
                sb.Append(b.ToString("x2") + " ");
                pch[i & 0x1F] = non_monospace(b) ? '.' : (Char)b;
            }
        }
        while ((++i & 0x1F) != 0);

        sb.Append(' ');
        sb.AppendLine(new String(pch, 0, 32));
    }
    return sb.ToString();
}

The code uses the following helpers to determine which characters should be shown as 'dots' in right-hand part.

static readonly ulong[] _nmb =
{
    0x00000000ffffe7ffUL,
    0x8000000000000000UL,
    0x00002000ffffffffUL,
    0x0000000000000000UL,
};

static bool non_monospace(byte b) => (_nmb[b >> 6] & 1UL << b) != 0;

Output of the above function looks like this (character width is 138 columns, scroll to the right to see the "human-readable" part):

00000000 47 49 46 38 39 61 0f 00 0f 00 91 ff 00 00 00 00 c0 c0 c0 ff ff 00 00 00 00 21 f9 04 01 00 00 01 GIF89a...................!......
00000020 00 2c 00 00 00 00 0f 00 0f 00 00 02 2c 8c 0d 99 c7 91 02 e1 62 20 5a 79 ea bd 00 6d 89 69 8a f8 .,..........,.......b Zy...m.i..
00000040 08 e5 a7 99 e9 17 9d ac 24 a2 21 68 89 1e ac b4 d9 db 51 ab da c8 8c 1a 05 00 3b                ........$.!h......Q.......;

Try: Encoding.Default.GetBytes

If that doesn't work, there are different types that you can specify (UTF-8, ASCII...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top