Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7988999
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T12:37:22+00:00 2026-06-04T12:37:22+00:00

I’m looking at an old helper method which I’ve been using for a while

  • 0

I’m looking at an old helper method which I’ve been using for a while to trace byte arrays to the output. I wrote it a long time ago and it’s been working fine, but I was wondering if there was a better way to do that (with less code). Linq came to my mind, but the solution which I have is awfully inefficient. What I’d need would be something along the lines of a “foreach16”, or some enumerator which instead of returning 1 element at a time, returned a group of elements of an enumerable. Besides me creating my own enumerator class, is there a built-in way of doing that?

The examples below have more information on what I’m trying to accomplish.

Original code

    static void PrintBytes(byte[] bytes)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            if (i > 0 && ((i % 16) == 0))
            {
                // end of line, flushes bytes and resets buffer
                Console.WriteLine("   {0}", sb.ToString());
                sb.Length = 0;
            }
            else if (i > 0 && ((i % 8) == 0))
            {
                Console.Write(" ");
                sb.Append(' ');
            }

            Console.Write(" {0:X2}", (int)bytes[i]);
            if (' ' <= bytes[i] && bytes[i] <= '~')
            {
                sb.Append((char)bytes[i]);
            }
            else
            {
                // non-ASCII or control chars are printed as '.'
                sb.Append('.');
            }
        }

        // flushes the last few bytes
        if ((bytes.Length % 16) > 0)
        {
            // prints spaces where the missing bytes would be
            int spacesToPrint = 3 * (16 - (bytes.Length % 16));
            if ((bytes.Length % 16) <= 8)
            {
                spacesToPrint++;
            }

            Console.Write(new string(' ', spacesToPrint));
        }

        Console.WriteLine("   {0}", sb.ToString());
    }

What I have now – this is what I tried to simplify the code. But I’m doing many Skip/Take, which increases the complexity of the code from linear to quadratic.

    static void PrintBytesV2(byte[] bytes)
    {
        for (int i = 0; i < bytes.Length; i += 16)
        {
            PrintLineV2(bytes, i, Math.Min(16, bytes.Length - i));
        }
    }

    static void PrintLineV2(byte[] array, int offset, int count)
    {
        Console.Write(
            string.Join(
                " ", 
                array
                    .Skip(offset)
                    .Take(count)
                    .Select((b, i) =>
                        ((i == 8) ? " " : "") +
                            string.Format("{0:X2}", (int)b))));

        Console.Write( 
            new string(
                ' ', 
                (16 - count) * 3 +
                    (count <= 8 ? 1 : 0)) + 
            "  ");

        Console.WriteLine(
            string.Join(
            "", 
            array
                .Skip(offset)
                .Take(count)
                .Select(b => (' ' <= b && b <= '~') ? (char)b : '.')));
    }

Notice that even if the new code as it is were linear, I’d likely stick with the original code since 1) it works; and 2) I think it’s more legible. But I can’t help wondering whether there is some way of iterating over groups.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T12:37:24+00:00Added an answer on June 4, 2026 at 12:37 pm

    OK well I’m not sure this is more readable, but here’s a solution that uses a Buffer extension method similar to that from Reactive Extensions.

    public static IEnumerable<IList<T>> Buffer<T>(this IEnumerable<T> orig, int count)
    {
        return orig.Select((o,i) => new { o, i })
                   .GroupBy(x => x.i / count, x => x.o)
                   .Select(g => g.ToList());
    }
    

    Given a block of 16 bytes, turn them into a string (goes at the end of each line):

    static string FormatAsString(IList<byte> bytes)
    {  
        return String.Join(" ", 
                     bytes.Buffer(8).Select(
                         bs => new String(bs.Select(b => ' ' <= b && b <= '~' ? (char)b : '.').ToArray())
                     )
               );
    }
    

    Given a block of bytes (usually 16 wide), turn them into a string representation of those bytes (goes at the beginning of each line):

    static string FormatAsBytes(IList<byte> bytes)
    {
        var blocks = 
            bytes.Buffer(8)
                 .Select(bs => String.Join(" ", 
                    bs.Select(b => String.Format("{0:X2}", (int)b)))
                 );
    
        return String.Join("  ", blocks);
    }
    

    Now if we turn the input bytes into blocks, then we can just run the above two on the output:

    static void PrintBytesWide(byte[] bytes, int width)
    {
        foreach (var line in bytes.Buffer(width))
        {
            Console.WriteLine("{0} {1}", FormatAsBytes(line).PadRight((width + 1) * 3, ' '), FormatAsString(line));
        }
    }
    

    To run with 16 byte blocks:

    var bytes = Encoding.UTF8.GetBytes("the quick brown fox");
    PrintBytesWide(bytes, 16);
    

    For me this returned basically the same output as your original;

    Original:

     74 68 65 20 71 75 69 63  6B 20 62 72 6F 77 6E 20   the quic k brown 
     66 6F 78                                           fox
    

    New:

    74 68 65 20 71 75 69 63  6B 20 62 72 6F 77 6E 20    the quic k brown 
    66 6F 78                                            fox
    

    But of course the beauty is that you can do different widths!

    PrintBytesWide(bytes, 8);
    
    74 68 65 20 71 75 69 63     the quic
    6B 20 62 72 6F 77 6E 20     k brown 
    66 6F 78                    fox
    
    PrintBytesWide(bytes, 24);
    
    74 68 65 20 71 75 69 63  6B 20 62 72 6F 77 6E 20  66 6F 78                  the quic k brown  fox
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.