Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I like both solutions. Here is another way that comes to my mind (probably not better).</p> <p><code> ((~((unsigned int)0) &lt;&lt; k) >> (k + n)) &lt;&lt; n </code></p> <p>EDIT: There was a bug in my previous version (it was without the unsigned int cast). The problem was that <code>~0 &gt;&gt; n</code> adds 1s at the front and not 0s.</p> <p>And yes this approach has one big downside; it assumes that you know the number of bits of the default integer type or in other words it assumes that you really know k, whereas the other solutions are independent of k. This makes my version less portable, or at least harder to port. (It also uses 3 shifts, and addition and a bitwise negation operator, which is two extra operations.)</p> <p><strong>So you would do better to use one of the other examples.</strong></p> <p>Here is a little test app, done by Jonathan Leffler, to compare and verify the output of the different solutions:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;limits.h&gt; enum { ULONG_BITS = (sizeof(unsigned long) * CHAR_BIT) }; static unsigned long set_mask_1(int k, int m, int n) { return ~(~0 &lt;&lt; m) &lt;&lt; n; } static unsigned long set_mask_2(int k, int m, int n) { return ((1 &lt;&lt; m) - 1) &lt;&lt; n; } static unsigned long set_mask_3(int k, int m, int n) { return ((~((unsigned long)0) &lt;&lt; k) &gt;&gt; (k + n)) &lt;&lt; n; } static int test_cases[][2] = { { 1, 0 }, { 1, 1 }, { 1, 2 }, { 1, 3 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 3, 4 }, { 3, 5 }, }; int main(void) { size_t i; for (i = 0; i &lt; 9; i++) { int m = test_cases[i][0]; int n = test_cases[i][1]; int k = ULONG_BITS - (m + n); printf("%d/%d/%d = 0x%08lX = 0x%08lX = 0x%08lX\n", k, m, n, set_mask_1(k, m, n), set_mask_2(k, m, n), set_mask_3(k, m, n)); } return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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