Note that there are some explanatory texts on larger screens.

plurals
  1. POAlgorithm for copying N bits at arbitrary position from one int to another
    primarykey
    data
    text
    <p>An interesting problem I've been pondering the past few days is how to copy one integer's bits into another integer at a given position in the destination integer. So, for example, given the destination integer <code>0xdeadbeef</code> and the source integer <code>0xabcd</code>, the idea would be to get a result of <code>0xabcdbeef</code> (given a destination position of 16 bits) or <code>0xdeabcdef</code> (given a destination position of 8 bits). </p> <p>With the arbitrary limitation of avoiding conditionals or loops (allowing myself to use just mathematical/bitwise operations), I developed the following function (C++)</p> <pre><code>int setbits(int destination, int source, int at, int numbits) { int ones = ((1&lt;&lt;(numbits))-1)&lt;&lt;at; return (ones|destination)^((~source&lt;&lt;at)&amp;ones); } </code></pre> <p>where <code>at</code> is the place where the source bits should be copied into the destination number (0-31) and <code>numbits</code> is the number of bits being copied from <code>source</code> (1-32). As far as I can tell, this algorithm works for all values except for <code>at</code> = 0 and <code>numbits</code> = 32 (the case when the entire destination integer is being overwritten by the source integer) due to the fact that 1&lt;&lt;32 results in 1 (since the shift wraps around) as opposed to 0. </p> <p>My questions are:</p> <ol> <li>How is this normally done? Are there any particularly notable algorithms used (by notable, I'm asking if there are any particularly efficient tricks that can be used to do this)?</li> <li>Does my algorithm work as well as I think it does (that is, works for all values except at = 0 and numbits = 32)?</li> <li>Related to 1), is there any way to do this only using mathematical/bitwise operators? The algorithm for all values is trivial using conditions or loops, so I'm not interested in that.</li> </ol> <p>Algorithm design is usually a weak point for me, so I have no idea whether or not my algorithm is 'as good as it gets' when only using mathematical/bitwise operations. Thanks</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    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