Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Really you're only doing four calculations, so <strong><em>readability seems way more important</em></strong> here than efficiency. My approach to make something like this more readable is to </p> <ol> <li>Extract common code to a function</li> <li>Put similar calculations together to make the patterns more obvious</li> <li>Get rid of the intermediate variable print_zeroes and be explicit about the cases in which you output bytes even if they're zero (i.e. the preceding byte was non-zero)</li> </ol> <p>I've changed the random code block into a function and changed a few variables (underscores are giving me trouble in the markdown preview screen). I've also assumed that <em>bytes</em> is being passed in, and that whoever is passing it in will pass us a pointer so we can modify it.</p> <p>Here's the code:</p> <pre><code>/* append byte b to stream, increment index */ /* really needs to check length of stream before appending */ void output( int i, unsigned char b, char stream[], int *index ) { printf("byte %d: 0x%02x\n", i, b); stream[(*index)++] = b; } void answer( char bytestream[], unsigned int *bytes, unsigned int n) { /* mask out four bytes from word n */ first = (n &amp; 0xFF000000) &gt;&gt; 24; second = (n &amp; 0x00FF0000) &gt;&gt; 16; third = (n &amp; 0x0000FF00) &gt;&gt; 8; fourth = (n &amp; 0x000000FF) &gt;&gt; 0; /* conditionally output each byte starting with the */ /* first non-zero byte */ if (first) output( 1, first, bytestream, bytes); if (first || second) output( 2, second, bytestream, bytes); if (first || second || third) output( 3, third, bytestream, bytes); if (first || second || third || fourth) output( 4, fourth, bytestream, bytes); } </code></pre> <p>Ever so slightly more efficient, and <strong><em>maybe</em></strong> easier to understand would be this modification to the last four if statements:</p> <pre><code> if (n&gt;0x00FFFFFF) output( 1, first, bytestream, bytes); if (n&gt;0x0000FFFF) output( 2, second, bytestream, bytes); if (n&gt;0x000000FF) output( 3, third, bytestream, bytes); if (1) output( 4, fourth, bytestream, bytes); </code></pre> <p>I agree, however, that compressing this field makes the receiving state machine overly complicated. But if you can't change the protocol, this code is much easier to read.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload