If you have two equal-sized buffers and you need to swap the over in memory:
[X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7 Y8 Y9]
becomes
[Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7 Y8 Y9 X0 X1 X2 X3 X4 X5 X6 X7 X8 X9]
It's easy to use a loop that swaps one machine register-sized chunk at a time:
void swapBufferHalves( U8 *buf, U32 start, U32 length ) {
register U64 *p1 = (U64*)&buf[ start ];
register U64 *p2 = (U64*)&buf[ start + ( length >> 1 ) ];
const U64 *pend = (U64*)(start + length);
register U64 temp;
assert( !( length & 1 ) );
assert( ( (U64)buf & 7ull ) == 0 );
while( p1 < pend ) {
temp = *p1;
*p1++ = *p2;
*p2++ = temp;
}
return;
}
But how to deal with the situation where the second 'half' of the buffer is shorter than the first:
[X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7]
becomes
[Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7 X0 X1 X2 X3 X4 X5 X6 X7 X8 X9]
Intuition tells me that this ought to be possible using 2 temporary registers; but the logic won't come?
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.