Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's the best method I could come up with for setting individual bits of a variable: Assume we need to set the first four bits of variable1 (a char or other byte long variable) to 1010</p> <pre><code>variable1 &amp;= 0b00001111; //Zero the first four bytes variable1 |= 0b10100000; //Set them to 1010, its important that any unaffected bits be zero </code></pre> <p>This could be extended to whatever bits desired by placing zeros in the first number corresponding to the bits which you wish to set (the first four in the example's case), and placing zeros in the second number corresponding to the bits which you wish to remain neutral in the second number (the last four in the example's case). The second number could also be derived by bit-shifting your desired value by the appropriate number of places (which would have been four in the example's case).</p> <p>In response to your comment this can be modified as follows to accommodate for increased variability:</p> <p>For this operation we will need two shifts assuming you wish to be able to modify non-starting and non-ending bits. There are two sets of bits in this case the first (from the left) set of unaffected bits and the second set. If you wish to modify four bits skipping the first bit from the left (1 <em>these four bits</em> 111 for a single byte), the first shift would be would be 7 and the second shift would be 5.</p> <pre><code>variable1 &amp;= ( ( 0b11111111 &lt;&lt; shift1 ) | 0b11111111 &gt;&gt; shift2 ); </code></pre> <p>Next the value we wish to assign needs to be shifted and or'ed in. However, we will need a third shift to account for how many bits we want to set. This shift (we'll call it <code>shift3</code>) is <code>shift1</code> minus the number of bits we wish to modify (as previously mentioned 4).</p> <pre><code>variable1 |= ( value &lt;&lt; shift3 ); </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. 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