<p>I want to shift the contents of an array of bytes by 12-bit to the left.</p>

<p>For example, starting with this array of type <code>uint8_t shift[10]</code>:</p>

<pre><code>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xBC}
</code></pre>

<p>I'd like to shift it to the left by 12-bits resulting in:</p>

<pre><code>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAB, 0xC0, 0x00}
</code></pre>

[{'answer_id': 29463, 'author': 'Joseph Pecoraro', 'author_id': 792, 'author_profile': 'https://Stackoverflow.com/users/792', 'pm_score': 2, 'selected': False, 'text': "<p>Lets make it the best way to shift <code>N</code> bits in the array of 8 bit integers.</p>\n\n<pre><code>N            - Total number of bits to shift\nF = (N / 8) - Full 8 bit integers shifted\nR = (N % 8) - Remaining bits that need to be shifted\n</code></pre>\n\n<p>I guess from here you would have to find the most optimal way to make use of this data to move around ints in an array.  Generic algorithms would be to apply the full integer shifts by starting from the right of the array and moving each integer <code>F</code> indexes.  Zero fill the newly empty spaces.  Then finally perform an <code>R</code> bit shift on all of the indexes, again starting from the right.</p>\n\n<p>In the case of shifting <code>0xBC</code> by <code>R</code> bits you can calculate the overflow by doing a bitwise AND, and the shift using the bitshift operator:</p>\n\n<pre><code>// 0xAB shifted 4 bits is:\n(0xAB &amp; 0x0F) &gt;&gt; 4   // is the overflow      (0x0A)\n0xAB &lt;&lt; 4            // is the shifted value (0xB0)\n</code></pre>\n\n<p>Keep in mind that the 4 bits is just a simple mask: 0x0F or just 0b00001111.  This is easy to calculate, dynamically build, or you can even use a simple static lookup table.</p>\n\n<p>I hope that is generic enough.  I'm not good with C/C++ at all so maybe someone can clean up my syntax or be more specific.</p>\n\n<p>Bonus:  If you're crafty with your C you might be able to fudge multiple array indexes into a single 16, 32, or even 64 bit integer and perform the shifts.  But that is prabably not very portable and I would recommend against this.  Just a possible optimization. </p>\n"}, {'answer_id': 29467, 'author': 'Nathan Fellman', 'author_id': 1084, 'author_profile': 'https://Stackoverflow.com/users/1084', 'pm_score': 0, 'selected': False, 'text': "<p>@Joseph, notice that the variables are 8 bits wide, while the shift is 12 bits wide.  Your solution works only for N &lt;= variable size.</p>\n\n<p>If you can assume your array is a multiple of 4 you can cast the array into an array of uint64_t and then work on that.  If it isn't a multiple of 4, you can work in 64-bit chunks on as much as you can and work on the remainder one by one.\nThis may be a bit more coding, but I think it's more elegant in the end.</p>\n"}, {'answer_id': 29492, 'author': 'Mike Haboustak', 'author_id': 2146, 'author_profile': 'https://Stackoverflow.com/users/2146', 'pm_score': 4, 'selected': True, 'text': "<p>Hurray for pointers! </p>\n\n<p>This code works by looking ahead 12 bits for each byte and copying the proper bits forward. 12 bits is the bottom half (nybble) of the next byte and the top half of 2 bytes away.</p>\n\n<pre><code>unsigned char length = 10;\nunsigned char data[10] = {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0A,0xBC};\nunsigned char *shift = data;\nwhile (shift &lt; data+(length-2)) {\n    *shift = (*(shift+1)&amp;0x0F)&lt;&lt;4 | (*(shift+2)&amp;0xF0)&gt;&gt;4;\n    shift++;\n}\n*(data+length-2) = (*(data+length-1)&amp;0x0F)&lt;&lt;4;\n*(data+length-1) = 0x00;\n</code></pre>\n\n<blockquote>\n  <p>Justin wrote:<br>\n  @Mike, your solution works, but does not carry.  </p>\n</blockquote>\n\n<p>Well, I'd say a normal shift operation does just that (called overflow), and just lets the extra bits fall off the right or left. It's simple enough to carry if you wanted to - just save the 12 bits before you start to shift. Maybe you want a circular shift, to put the overflowed bits back at the bottom? Maybe you want to realloc the array and make it larger? Return the overflow to the caller? Return a boolean if non-zero data was overflowed? You'd have to define what carry means to you.</p>\n\n<pre><code>unsigned char overflow[2];\n*overflow = (*data&amp;0xF0)&gt;&gt;4;\n*(overflow+1) = (*data&amp;0x0F)&lt;&lt;4 | (*(data+1)&amp;0xF0)&gt;&gt;4;\nwhile (shift &lt; data+(length-2)) {\n    /* normal shifting */\n}  \n/* now would be the time to copy it back if you want to carry it somewhere */\n*(data+length-2) = (*(data+length-1)&amp;0x0F)&lt;&lt;4 | (*(overflow)&amp;0x0F);\n*(data+length-1) = *(overflow+1);  \n\n/* You could return a 16-bit carry int, \n * but endian-ness makes that look weird \n * if you care about the physical layout */\nunsigned short carry = *(overflow+1)&lt;&lt;8 | *overflow;\n</code></pre>\n"}, {'answer_id': 29504, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 3, 'selected': False, 'text': "<p>Here's my solution, but even more importantly my approach to solving the problem.</p>\n\n<p>I approached the problem by</p>\n\n<ul>\n<li>drawing the memory cells and drawing arrows from the destination to the source.</li>\n<li>made a table showing the above drawing.</li>\n<li>labeling each row in the table with the relative byte address.</li>\n</ul>\n\n<p>This showed me the pattern:</p>\n\n<ul>\n<li>let <code>iL</code> be the low nybble (half byte) of <code>a[i]</code></li>\n<li>let <code>iH</code> be the high nybble of <code>a[i]</code></li>\n<li><code>iH = (i+1)L</code></li>\n<li><code>iL = (i+2)H</code></li>\n</ul>\n\n<p>This pattern holds for all bytes.</p>\n\n<p>Translating into C, this means:</p>\n\n<pre><code>a[i] = (iH &lt;&lt; 4) OR iL\na[i] = ((a[i+1] &amp; 0x0f) &lt;&lt; 4) | ((a[i+2] &amp; 0xf0) &gt;&gt; 4)\n</code></pre>\n\n<p>We now make three more observations:</p>\n\n<ul>\n<li>since we carry out the assignments left to right, we don't need to store any values in temporary variables.</li>\n<li>we will have a special case for the tail: all <code>12 bits</code> at the end will be zero.</li>\n<li>we must avoid reading undefined memory past the array.  since we never read more than <code>a[i+2]</code>, this only affects the last two bytes</li>\n</ul>\n\n<p>So, we</p>\n\n<ul>\n<li>handle the general case by looping for <code>N-2 bytes</code> and performing the general calculation above</li>\n<li>handle the next to last byte by it by setting <code>iH = (i+1)L</code></li>\n<li>handle the last byte by setting it to <code>0</code></li>\n</ul>\n\n<p>given <code>a</code> with length <code>N</code>, we get:</p>\n\n<pre><code>for (i = 0; i &lt; N - 2; ++i) {\n    a[i] = ((a[i+1] &amp; 0x0f) &lt;&lt; 4) | ((a[i+2] &amp; 0xf0) &gt;&gt; 4);\n}\na[N-2] = (a[N-1) &amp; 0x0f) &lt;&lt; 4;\na[N-1] = 0;\n</code></pre>\n\n<p>And there you have it... the array is shifted left by <code>12 bits</code>.  It could easily be generalized to shifting <code>N bits</code>, noting that there will be <code>M</code> assignment statements where <code>M = number of bits modulo 8</code>, I believe.</p>\n\n<p>The loop could be made more efficient on some machines by translating to pointers</p>\n\n<pre><code>for (p = a, p2=a+N-2; p != p2; ++p) {\n    *p = ((*(p+1) &amp; 0x0f) &lt;&lt; 4) | (((*(p+2) &amp; 0xf0) &gt;&gt; 4);\n}\n</code></pre>\n\n<p>and by using the largest integer data type supported by the CPU.</p>\n\n<p>(I've just typed this in, so now would be a good time for somebody to review the code, especially since bit twiddling is notoriously easy to get wrong.)</p>\n"}, {'answer_id': 29508, 'author': 'DMC', 'author_id': 3148, 'author_profile': 'https://Stackoverflow.com/users/3148', 'pm_score': 1, 'selected': False, 'text': '<p>The 32 bit version... :-) Handles 1 &lt;= count &lt;= num_words</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nunsigned int array[] = {0x12345678,0x9abcdef0,0x12345678,0x9abcdef0,0x66666666};\n\nint main(void) {\n  int count;\n  unsigned int *from, *to;\n  from = &amp;array[0];\n  to = &amp;array[0];\n  count = 5;\n\n  while (count-- &gt; 1) {\n    *to++ = (*from&lt;&lt;12) | ((*++from&gt;&gt;20)&amp;0xfff);\n  };\n  *to = (*from&lt;&lt;12);\n\n  printf("%x\\n", array[0]);\n  printf("%x\\n", array[1]);\n  printf("%x\\n", array[2]);\n  printf("%x\\n", array[3]);\n  printf("%x\\n", array[4]);\n\n  return 0;\n}\n</code></pre>\n'}, {'answer_id': 29514, 'author': 'Justin Tanner', 'author_id': 609, 'author_profile': 'https://Stackoverflow.com/users/609', 'pm_score': 2, 'selected': False, 'text': "<p>Here a working solution, using temporary variables:</p>\n\n<pre><code>void shift_4bits_left(uint8_t* array, uint16_t size)\n{\n    int i;\n    uint8_t shifted = 0x00;    \n    uint8_t overflow = (0xF0 &amp; array[0]) &gt;&gt; 4;\n\n    for (i = (size - 1); i &gt;= 0; i--)\n    {\n        shifted = (array[i] &lt;&lt; 4) | overflow;\n        overflow = (0xF0 &amp; array[i]) &gt;&gt; 4;\n        array[i] = shifted;\n    }\n}\n</code></pre>\n\n<p>Call this function 3 times for a 12-bit shift.</p>\n\n<p>Mike's solution maybe faster, due to the use of temporary variables.</p>\n"}, {'answer_id': 29532, 'author': 'Dominic Cooney', 'author_id': 878, 'author_profile': 'https://Stackoverflow.com/users/878', 'pm_score': 0, 'selected': False, 'text': '<p>There are a couple of edge-cases which make this a neat problem:</p>\n\n<ul>\n<li>the input array might be empty</li>\n<li>the last and next-to-last bits need to be treated specially, because they have zero bits shifted into them</li>\n</ul>\n\n<p>Here\'s a simple solution which loops over the array copying the low-order nibble of the next byte into its high-order nibble, and the high-order nibble of the next-next (+2) byte into its low-order nibble. To save dereferencing the look-ahead pointer twice, it maintains a two-element buffer with the "last" and "next" bytes: </p>\n\n<pre><code>void shl12(uint8_t *v, size_t length) {\n  if (length == 0) {\n    return; // nothing to do\n  }\n\n  if (length &gt; 1) {\n    uint8_t last_byte, next_byte;\n    next_byte = *(v + 1);\n\n    for (size_t i = 0; i + 2 &lt; length; i++, v++) {\n      last_byte = next_byte;\n      next_byte = *(v + 2);\n      *v = ((last_byte &amp; 0x0f) &lt;&lt; 4) | (((next_byte) &amp; 0xf0) &gt;&gt; 4);\n    }\n\n    // the next-to-last byte is half-empty\n    *(v++) = (next_byte &amp; 0x0f) &lt;&lt; 4;\n  }\n\n  // the last byte is always empty\n  *v = 0;\n}\n</code></pre>\n\n<p>Consider the boundary cases, which activate successively more parts of the function:</p>\n\n<ul>\n<li>When <code>length</code> is zero, we bail out without touching memory.</li>\n<li>When <code>length</code> is one, we set the one and only element to zero.</li>\n<li>When <code>length</code> is two, we set the high-order nibble of the first byte to low-order nibble of the second byte (that is, bits 12-16), and the second byte to zero. We don\'t activate the loop.</li>\n<li>When <code>length</code> is greater than two we hit the loop, shuffling the bytes across the two-element buffer.</li>\n</ul>\n\n<p>If efficiency is your goal, the answer probably depends largely on your machine\'s architecture. Typically you should maintain the two-element buffer, but handle a machine word (32/64 bit unsigned integer) at a time. If you\'re shifting a lot of data it will be worthwhile treating the first few bytes as a special case so that you can get your machine word pointers word-aligned. Most CPUs access memory more efficiently if the accesses fall on machine word boundaries. Of course, the trailing bytes have to be handled specially too so you don\'t touch memory past the end of the array.</p>\n'}]
['https://Stackoverflow.com/questions/29437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/609/']