<p>How do I set, clear, and toggle a bit?</p>

[{'answer_id': 47990, 'author': 'Paige Ruten', 'author_id': 813, 'author_profile': 'https://Stackoverflow.com/users/813', 'pm_score': 13, 'selected': True, 'text': '<h1>Setting a bit</h1>\n<p>Use the bitwise OR operator (<code>|</code>) to set a bit.</p>\n<pre><code>number |= 1UL &lt;&lt; n;\n</code></pre>\n<p>That will set the <code>n</code>th bit of <code>number</code>. <code>n</code> should be zero, if you want to set the <code>1</code>st bit and so on upto <code>n-1</code>, if you want to set the <code>n</code>th bit.</p>\n<p>Use <code>1ULL</code> if <code>number</code> is wider than <code>unsigned long</code>; promotion of <code>1UL &lt;&lt; n</code> doesn\'t happen until after evaluating <code>1UL &lt;&lt; n</code> where it\'s undefined behaviour to shift by more than the width of a <code>long</code>.  The same applies to all the rest of the examples.</p>\n<h1>Clearing a bit</h1>\n<p>Use the bitwise AND operator (<code>&amp;</code>) to clear a bit.</p>\n<pre><code>number &amp;= ~(1UL &lt;&lt; n);\n</code></pre>\n<p>That will clear the <code>n</code>th bit of <code>number</code>. You must invert the bit string with the bitwise NOT operator (<code>~</code>), then AND it.</p>\n<h1>Toggling a bit</h1>\n<p>The XOR operator (<code>^</code>) can be used to toggle a bit.</p>\n<pre><code>number ^= 1UL &lt;&lt; n;\n</code></pre>\n<p>That will toggle the <code>n</code>th bit of <code>number</code>.</p>\n<h1>Checking a bit</h1>\n<p>You didn\'t ask for this, but I might as well add it.</p>\n<p>To check a bit, shift the number n to the right, then bitwise AND it:</p>\n<pre><code>bit = (number &gt;&gt; n) &amp; 1U;\n</code></pre>\n<p>That will put the value of the <code>n</code>th bit of <code>number</code> into the variable <code>bit</code>.</p>\n<h1>Changing the <em>n</em>th bit to <em>x</em></h1>\n<p>Setting the <code>n</code>th bit to either <code>1</code> or <code>0</code> can be achieved with the following on a 2\'s complement C++ implementation:</p>\n<pre><code>number ^= (-x ^ number) &amp; (1UL &lt;&lt; n);\n</code></pre>\n<p>Bit <code>n</code> will be set if <code>x</code> is <code>1</code>, and cleared if <code>x</code> is <code>0</code>.  If <code>x</code> has some other value, you get garbage.  <code>x = !!x</code> will booleanize it to 0 or 1.</p>\n<p>To make this independent of 2\'s complement negation behaviour (where <code>-1</code> has all bits set, unlike on a 1\'s complement or sign/magnitude C++ implementation), use unsigned negation.</p>\n<pre><code>number ^= (-(unsigned long)x ^ number) &amp; (1UL &lt;&lt; n);\n</code></pre>\n<p>or</p>\n<pre><code>unsigned long newbit = !!x;    // Also booleanize to force 0 or 1\nnumber ^= (-newbit ^ number) &amp; (1UL &lt;&lt; n);\n</code></pre>\n<p>It\'s generally a good idea to use unsigned types for portable bit manipulation.</p>\n<p>or</p>\n<pre><code>number = (number &amp; ~(1UL &lt;&lt; n)) | (x &lt;&lt; n);\n</code></pre>\n<p><code>(number &amp; ~(1UL &lt;&lt; n))</code> will clear the <code>n</code>th bit and <code>(x &lt;&lt; n)</code> will set the <code>n</code>th bit to <code>x</code>.</p>\n<p>It\'s also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like <a href="https://stackoverflow.com/a/263738/52074">the community wiki answer further down</a>) or some sort of encapsulation.</p>\n'}, {'answer_id': 50691, 'author': 'dmckee --- ex-moderator kitten', 'author_id': 2509, 'author_profile': 'https://Stackoverflow.com/users/2509', 'pm_score': 7, 'selected': False, 'text': '<p>It is sometimes worth using an <code>enum</code> to <em>name</em> the bits:</p>\n<pre class="lang-cpp prettyprint-override"><code>enum ThingFlags = {\n  ThingMask  = 0x0000,\n  ThingFlag0 = 1 &lt;&lt; 0,\n  ThingFlag1 = 1 &lt;&lt; 1,\n  ThingError = 1 &lt;&lt; 8,\n}\n</code></pre>\n<p>Then use the <em>names</em> later on. I.e. write</p>\n<pre class="lang-cpp prettyprint-override"><code>thingstate |= ThingFlag1;\nthingstate &amp;= ~ThingFlag0;\nif (thing &amp; ThingError) {...}\n</code></pre>\n<p>to set, clear and test. This way you hide the magic numbers from the rest of your code.</p>\n<p>Other than that, I endorse <a href="https://stackoverflow.com/questions/47981/how-do-i-set-clear-and-toggle-a-single-bit/47990#47990">Paige Ruten\'s solution</a>.</p>\n'}, {'answer_id': 55584, 'author': 'Ferruccio', 'author_id': 4086, 'author_profile': 'https://Stackoverflow.com/users/4086', 'pm_score': 8, 'selected': False, 'text': "<p>The other option is to use bit fields:</p>\n\n<pre><code>struct bits {\n    unsigned int a:1;\n    unsigned int b:1;\n    unsigned int c:1;\n};\n\nstruct bits mybits;\n</code></pre>\n\n<p>defines a 3-bit field (actually, it's three 1-bit felds). Bit operations now become a bit (haha) simpler:</p>\n\n<p>To set or clear a bit:</p>\n\n<pre><code>mybits.b = 1;\nmybits.c = 0;\n</code></pre>\n\n<p>To toggle a bit:</p>\n\n<pre><code>mybits.a = !mybits.a;\nmybits.b = ~mybits.b;\nmybits.c ^= 1;  /* all work */\n</code></pre>\n\n<p>Checking a bit:</p>\n\n<pre><code>if (mybits.c)  //if mybits.c is non zero the next line below will execute\n</code></pre>\n\n<p>This only works with fixed-size bit fields. Otherwise you have to resort to the bit-twiddling techniques described in previous posts.</p>\n"}, {'answer_id': 79163, 'author': 'yogeesh', 'author_id': 9030, 'author_profile': 'https://Stackoverflow.com/users/9030', 'pm_score': 6, 'selected': False, 'text': '<h2>From <a href="http://snippets.org/code/temp/snip-c.zip" rel="noreferrer">snip-c.zip</a>\'s bitops.h:</h2>\n\n<pre><code>/*\n**  Bit set, clear, and test operations\n**\n**  public domain snippet by Bob Stout\n*/\n\ntypedef enum {ERROR = -1, FALSE, TRUE} LOGICAL;\n\n#define BOOL(x) (!(!(x)))\n\n#define BitSet(arg,posn) ((arg) | (1L &lt;&lt; (posn)))\n#define BitClr(arg,posn) ((arg) &amp; ~(1L &lt;&lt; (posn)))\n#define BitTst(arg,posn) BOOL((arg) &amp; (1L &lt;&lt; (posn)))\n#define BitFlp(arg,posn) ((arg) ^ (1L &lt;&lt; (posn)))\n</code></pre>\n\n<p>OK, let\'s analyze things...</p>\n\n<p>The common expression that you seem to be having problems with in all of these is "(1L &lt;&lt; (posn))". All this does is create a mask with a single bit on\nand which will work with any integer type. The "posn" argument specifies the\nposition where you want the bit. If posn==0, then this expression will\nevaluate to:</p>\n\n<pre><code>0000 0000 0000 0000 0000 0000 0000 0001 binary.\n</code></pre>\n\n<p>If posn==8, it will evaluate to:</p>\n\n<pre><code>0000 0000 0000 0000 0000 0001 0000 0000 binary.\n</code></pre>\n\n<p>In other words, it simply creates a field of 0\'s with a 1 at the specified\nposition. The only tricky part is in the BitClr() macro where we need to set\na single 0 bit in a field of 1\'s. This is accomplished by using the 1\'s\ncomplement of the same expression as denoted by the tilde (~) operator.</p>\n\n<p>Once the mask is created it\'s applied to the argument just as you suggest,\nby use of the bitwise and (&amp;), or (|), and xor (^) operators. Since the mask\nis of type long, the macros will work just as well on char\'s, short\'s, int\'s,\nor long\'s.</p>\n\n<p>The bottom line is that this is a general solution to an entire class of\nproblems. It is, of course, possible and even appropriate to rewrite the\nequivalent of any of these macros with explicit mask values every time you\nneed one, but why do it? Remember, the macro substitution occurs in the\npreprocessor and so the generated code will reflect the fact that the values\nare considered constant by the compiler - i.e. it\'s just as efficient to use\nthe generalized macros as to "reinvent the wheel" every time you need to do\nbit manipulation. </p>\n\n<p>Unconvinced? Here\'s some test code - I used Watcom C with full optimization\nand without using _cdecl so the resulting disassembly would be as clean as\npossible:</p>\n\n<p>----[ TEST.C ]----------------------------------------------------------------</p>\n\n<pre><code>#define BOOL(x) (!(!(x)))\n\n#define BitSet(arg,posn) ((arg) | (1L &lt;&lt; (posn)))\n#define BitClr(arg,posn) ((arg) &amp; ~(1L &lt;&lt; (posn)))\n#define BitTst(arg,posn) BOOL((arg) &amp; (1L &lt;&lt; (posn)))\n#define BitFlp(arg,posn) ((arg) ^ (1L &lt;&lt; (posn)))\n\nint bitmanip(int word)\n{\n      word = BitSet(word, 2);\n      word = BitSet(word, 7);\n      word = BitClr(word, 3);\n      word = BitFlp(word, 9);\n      return word;\n}\n</code></pre>\n\n<p>----[ TEST.OUT (disassembled) ]-----------------------------------------------</p>\n\n<pre><code>Module: C:\\BINK\\tst.c\nGroup: \'DGROUP\' CONST,CONST2,_DATA,_BSS\n\nSegment: _TEXT  BYTE   00000008 bytes  \n 0000  0c 84             bitmanip_       or      al,84H    ; set bits 2 and 7\n 0002  80 f4 02                          xor     ah,02H    ; flip bit 9 of EAX (bit 1 of AH)\n 0005  24 f7                             and     al,0f7H\n 0007  c3                                ret     \n\nNo disassembly errors\n</code></pre>\n\n<p>----[ finis ]----------------------------------------------------------------- </p>\n'}, {'answer_id': 83645, 'author': 'Tim Ring', 'author_id': 3685, 'author_profile': 'https://Stackoverflow.com/users/3685', 'pm_score': 4, 'selected': False, 'text': "<p>If you're doing a lot of bit twiddling you might want to use masks which will make the whole thing quicker. The following functions are very fast and are still flexible (they allow bit twiddling in bit maps of any size).</p>\n\n<pre><code>const unsigned char TQuickByteMask[8] =\n{\n   0x01, 0x02, 0x04, 0x08,\n   0x10, 0x20, 0x40, 0x80,\n};\n\n\n/** Set bit in any sized bit mask.\n *\n * @return    none\n *\n * @param     bit    - Bit number.\n * @param     bitmap - Pointer to bitmap.\n */\nvoid TSetBit( short bit, unsigned char *bitmap)\n{\n    short n, x;\n\n    x = bit / 8;        // Index to byte.\n    n = bit % 8;        // Specific bit in byte.\n\n    bitmap[x] |= TQuickByteMask[n];        // Set bit.\n}\n\n\n/** Reset bit in any sized mask.\n *\n * @return  None\n *\n * @param   bit    - Bit number.\n * @param   bitmap - Pointer to bitmap.\n */\nvoid TResetBit( short bit, unsigned char *bitmap)\n{\n    short n, x;\n\n    x = bit / 8;        // Index to byte.\n    n = bit % 8;        // Specific bit in byte.\n\n    bitmap[x] &amp;= (~TQuickByteMask[n]);    // Reset bit.\n}\n\n\n/** Toggle bit in any sized bit mask.\n *\n * @return   none\n *\n * @param   bit    - Bit number.\n * @param   bitmap - Pointer to bitmap.\n */\nvoid TToggleBit( short bit, unsigned char *bitmap)\n{\n    short n, x;\n\n    x = bit / 8;        // Index to byte.\n    n = bit % 8;        // Specific bit in byte.\n\n    bitmap[x] ^= TQuickByteMask[n];        // Toggle bit.\n}\n\n\n/** Checks specified bit.\n *\n * @return  1 if bit set else 0.\n *\n * @param   bit    - Bit number.\n * @param   bitmap - Pointer to bitmap.\n */\nshort TIsBitSet( short bit, const unsigned char *bitmap)\n{\n    short n, x;\n\n    x = bit / 8;    // Index to byte.\n    n = bit % 8;    // Specific bit in byte.\n\n    // Test bit (logigal AND).\n    if (bitmap[x] &amp; TQuickByteMask[n])\n        return 1;\n\n    return 0;\n}\n\n\n/** Checks specified bit.\n *\n * @return  1 if bit reset else 0.\n *\n * @param   bit    - Bit number.\n * @param   bitmap - Pointer to bitmap.\n */\nshort TIsBitReset( short bit, const unsigned char *bitmap)\n{\n    return TIsBitSet(bit, bitmap) ^ 1;\n}\n\n\n/** Count number of bits set in a bitmap.\n *\n * @return   Number of bits set.\n *\n * @param    bitmap - Pointer to bitmap.\n * @param    size   - Bitmap size (in bits).\n *\n * @note    Not very efficient in terms of execution speed. If you are doing\n *        some computationally intense stuff you may need a more complex\n *        implementation which would be faster (especially for big bitmaps).\n *        See (http://graphics.stanford.edu/~seander/bithacks.html).\n */\nint TCountBits( const unsigned char *bitmap, int size)\n{\n    int i, count = 0;\n\n    for (i=0; i&lt;size; i++)\n        if (TIsBitSet(i, bitmap))\n            count++;\n\n    return count;\n}\n</code></pre>\n\n<p>Note, to set bit 'n' in a 16 bit integer you do the following:</p>\n\n<pre><code>TSetBit( n, &amp;my_int);\n</code></pre>\n\n<p>It's up to you to ensure that the bit number is within the range of the bit map that you pass. Note that for little endian processors that bytes, words, dwords, qwords, etc., map correctly to each other in memory (main reason that little endian processors are 'better' than big-endian processors, ah, I feel a flame war coming on...).</p>\n"}, {'answer_id': 88934, 'author': 'Martin York', 'author_id': 14065, 'author_profile': 'https://Stackoverflow.com/users/14065', 'pm_score': 9, 'selected': False, 'text': '<p>Using the Standard C++ Library: <a href="http://en.cppreference.com/w/cpp/utility/bitset" rel="noreferrer"><code>std::bitset&lt;N&gt;</code></a>.</p>\n\n<p>Or the <a href="http://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29" rel="noreferrer">Boost</a> version: <a href="http://www.boost.org/doc/libs/release/libs/dynamic_bitset/dynamic_bitset.html" rel="noreferrer"><code>boost::dynamic_bitset</code></a>.</p>\n\n<p>There is no need to roll your own:</p>\n\n<pre><code>#include &lt;bitset&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n    std::bitset&lt;5&gt; x;\n\n    x[1] = 1;\n    x[2] = 0;\n    // Note x[0-4]  valid\n\n    std::cout &lt;&lt; x &lt;&lt; std::endl;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>[Alpha:] &gt; ./a.out\n00010\n</code></pre>\n\n<p>The Boost version allows a runtime sized bitset compared with a <a href="https://en.wikipedia.org/wiki/C%2B%2B_Standard_Library" rel="noreferrer">standard library</a> compile-time sized bitset.</p>\n'}, {'answer_id': 263738, 'author': 'Steve Karg', 'author_id': 9016, 'author_profile': 'https://Stackoverflow.com/users/9016', 'pm_score': 8, 'selected': False, 'text': "<p>I use macros defined in a header file to handle bit set and clear:</p>\n<pre><code>/* a=target variable, b=bit number to act upon 0-n */\n#define BIT_SET(a,b) ((a) |= (1ULL&lt;&lt;(b)))\n#define BIT_CLEAR(a,b) ((a) &amp;= ~(1ULL&lt;&lt;(b)))\n#define BIT_FLIP(a,b) ((a) ^= (1ULL&lt;&lt;(b)))\n#define BIT_CHECK(a,b) (!!((a) &amp; (1ULL&lt;&lt;(b))))        // '!!' to make sure this returns 0 or 1\n\n#define BITMASK_SET(x, mask) ((x) |= (mask))\n#define BITMASK_CLEAR(x, mask) ((x) &amp;= (~(mask)))\n#define BITMASK_FLIP(x, mask) ((x) ^= (mask))\n#define BITMASK_CHECK_ALL(x, mask) (!(~(x) &amp; (mask)))\n#define BITMASK_CHECK_ANY(x, mask) ((x) &amp; (mask))\n</code></pre>\n"}, {'answer_id': 268356, 'author': 'Roddy', 'author_id': 1737, 'author_profile': 'https://Stackoverflow.com/users/1737', 'pm_score': 5, 'selected': False, 'text': "<p>The bitfield approach has other advantages in the embedded arena. You can define a struct that maps directly onto the bits in a particular hardware register.</p>\n\n<pre><code>struct HwRegister {\n    unsigned int errorFlag:1;  // one-bit flag field\n    unsigned int Mode:3;       // three-bit mode field\n    unsigned int StatusCode:4;  // four-bit status code\n};\n\nstruct HwRegister CR3342_AReg;\n</code></pre>\n\n<p>You need to be aware of the bit packing order - I think it's MSB first, but this may be implementation-dependent. Also, verify how your compiler handlers fields crossing byte boundaries.</p>\n\n<p>You can then read, write, test the individual values as before.</p>\n"}, {'answer_id': 410101, 'author': 'John Zwinck', 'author_id': 4323, 'author_profile': 'https://Stackoverflow.com/users/4323', 'pm_score': 5, 'selected': False, 'text': '<h2>Check a bit at an arbitrary location in a variable of arbitrary type:</h2>\n\n<pre><code>#define bit_test(x, y)  ( ( ((const char*)&amp;(x))[(y)&gt;&gt;3] &amp; 0x80 &gt;&gt; ((y)&amp;0x07)) &gt;&gt; (7-((y)&amp;0x07) ) )\n</code></pre>\n\n<p><strong>Sample usage:</strong></p>\n\n<pre><code>int main(void)\n{\n    unsigned char arr[8] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };\n\n    for (int ix = 0; ix &lt; 64; ++ix)\n        printf("bit %d is %d\\n", ix, bit_test(arr, ix));\n\n    return 0;\n}\n</code></pre>\n\n<p><strong>Notes:</strong>\nThis is designed to be fast (given its flexibility) and non-branchy.  It results in efficient SPARC machine code when compiled Sun Studio 8; I\'ve also tested it using MSVC++ 2008 on amd64.  It\'s possible to make similar macros for setting and clearing bits.  The key difference of this solution compared with many others here is that it works for any location in pretty much any type of variable.</p>\n'}, {'answer_id': 740953, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Use this:</p>\n\n<pre><code>int ToggleNthBit ( unsigned char n, int num )\n{\n    if(num &amp; (1 &lt;&lt; n))\n        num &amp;= ~(1 &lt;&lt; n);\n    else\n        num |= (1 &lt;&lt; n);\n\n    return num;\n}\n</code></pre>\n'}, {'answer_id': 991546, 'author': 'bill', 'author_id': 121958, 'author_profile': 'https://Stackoverflow.com/users/121958', 'pm_score': 5, 'selected': False, 'text': '<p>More general, for arbitrary sized bitmaps:</p>\n\n<pre><code>#define BITS 8\n#define BIT_SET(  p, n) (p[(n)/BITS] |=  (0x80&gt;&gt;((n)%BITS)))\n#define BIT_CLEAR(p, n) (p[(n)/BITS] &amp;= ~(0x80&gt;&gt;((n)%BITS)))\n#define BIT_ISSET(p, n) (p[(n)/BITS] &amp;   (0x80&gt;&gt;((n)%BITS)))\n</code></pre>\n'}, {'answer_id': 3234773, 'author': 'R.. GitHub STOP HELPING ICE', 'author_id': 379897, 'author_profile': 'https://Stackoverflow.com/users/379897', 'pm_score': 5, 'selected': False, 'text': "<p>Here's my favorite bit arithmetic macro, which works for any type of unsigned integer array from <code>unsigned char</code> up to <code>size_t</code> (which is the biggest type that should be efficient to work with):</p>\n\n<pre><code>#define BITOP(a,b,op) \\\n ((a)[(size_t)(b)/(8*sizeof *(a))] op ((size_t)1&lt;&lt;((size_t)(b)%(8*sizeof *(a)))))\n</code></pre>\n\n<p>To set a bit:</p>\n\n<pre><code>BITOP(array, bit, |=);\n</code></pre>\n\n<p>To clear a bit:</p>\n\n<pre><code>BITOP(array, bit, &amp;=~);\n</code></pre>\n\n<p>To toggle a bit:</p>\n\n<pre><code>BITOP(array, bit, ^=);\n</code></pre>\n\n<p>To test a bit:</p>\n\n<pre><code>if (BITOP(array, bit, &amp;)) ...\n</code></pre>\n\n<p>etc.</p>\n"}, {'answer_id': 9488379, 'author': 'Gokul Naathan', 'author_id': 1190788, 'author_profile': 'https://Stackoverflow.com/users/1190788', 'pm_score': 4, 'selected': False, 'text': '<p>This program is to change any data bit from 0 to 1 or 1 to 0:</p>\n\n<pre><code>{\n    unsigned int data = 0x000000F0;\n    int bitpos = 4;\n    int bitvalue = 1;\n    unsigned int bit = data;\n    bit = (bit&gt;&gt;bitpos)&amp;0x00000001;\n    int invbitvalue = 0x00000001&amp;(~bitvalue);\n    printf("%x\\n",bit);\n\n    if (bitvalue == 0)\n    {\n        if (bit == 0)\n            printf("%x\\n", data);\n        else\n        {\n             data = (data^(invbitvalue&lt;&lt;bitpos));\n             printf("%x\\n", data);\n        }\n    }\n    else\n    {\n        if (bit == 1)\n            printf("elseif %x\\n", data);\n        else\n        {\n            data = (data|(bitvalue&lt;&lt;bitpos));\n            printf("else %x\\n", data);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 10899060, 'author': 'kapilddit', 'author_id': 555911, 'author_profile': 'https://Stackoverflow.com/users/555911', 'pm_score': 5, 'selected': False, 'text': '<p>For the beginner I would like to explain a bit more with an example:</p>\n\n<p>Example:</p>\n\n<pre><code>value is 0x55;\nbitnum : 3rd.\n</code></pre>\n\n<p>The <code>&amp;</code> operator is used check the bit:</p>\n\n<pre><code>0101 0101\n&amp;\n0000 1000\n___________\n0000 0000 (mean 0: False). It will work fine if the third bit is 1 (then the answer will be True)\n</code></pre>\n\n<p>Toggle or Flip:</p>\n\n<pre><code>0101 0101\n^\n0000 1000\n___________\n0101 1101 (Flip the third bit without affecting other bits)\n</code></pre>\n\n<p><code>|</code> operator: set the bit</p>\n\n<pre><code>0101 0101\n|\n0000 1000\n___________\n0101 1101 (set the third bit without affecting other bits)\n</code></pre>\n'}, {'answer_id': 11036329, 'author': 'John U', 'author_id': 1389218, 'author_profile': 'https://Stackoverflow.com/users/1389218', 'pm_score': 5, 'selected': False, 'text': '<p>As this is tagged "embedded" I\'ll assume you\'re using a microcontroller. All of the above suggestions are valid &amp; work (read-modify-write, unions, structs, etc.).</p>\n\n<p>However, during a bout of oscilloscope-based debugging I was amazed to find that these methods have a considerable overhead in CPU cycles compared to writing a value directly to the micro\'s PORTnSET / PORTnCLEAR registers which makes a real difference where there are tight loops / high-frequency ISR\'s toggling pins.</p>\n\n<p>For those unfamiliar: In my example, the micro has a general pin-state register PORTn which reflects the output pins, so doing PORTn |= BIT_TO_SET results in a read-modify-write to that register. However, the PORTnSET / PORTnCLEAR registers take a \'1\' to mean "please make this bit 1" (SET) or "please make this bit zero" (CLEAR) and a \'0\' to mean "leave the pin alone". so, you end up with two port addresses depending whether you\'re setting or clearing the bit (not always convenient) but a <em>much</em> faster reaction and smaller assembled code.</p>\n'}, {'answer_id': 14087800, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Visual C 2010, and perhaps many other compilers, have direct support for boolean operations built in. A bit has two possible values, just like a boolean, so we can use booleans instead - even if they take up more space than a single bit in memory in this representation. This works, even the <code>sizeof()</code> operator works properly. </p>\n\n<pre><code>bool    IsGph[256], IsNotGph[256];\n\n//  Initialize boolean array to detect printable characters\nfor(i=0; i&lt;sizeof(IsGph); i++)  {\n    IsGph[i] = isgraph((unsigned char)i);\n}\n</code></pre>\n\n<p>So, to your question, <code>IsGph[i] =1</code>, or <code>IsGph[i] =0</code> make setting and clearing bools easy.</p>\n\n<p>To find unprintable characters:</p>\n\n<pre><code>//  Initialize boolean array to detect UN-printable characters, \n//  then call function to toggle required bits true, while initializing a 2nd\n//  boolean array as the complement of the 1st.\nfor(i=0; i&lt;sizeof(IsGph); i++)  {\n    if(IsGph[i])    {\n         IsNotGph[i] = 0;\n    }   else   {\n         IsNotGph[i] = 1;\n    }\n}\n</code></pre>\n\n<p>Note there is nothing "special" about this code. It treats a bit like an integer - which technically, it is. A 1 bit integer that can hold 2 values, and 2 values only.</p>\n\n<p>I once used this approach to find duplicate loan records, where loan_number was the ISAM key, using the 6-digit loan number as an index into the bit array. Savagely fast, and after 8 months, proved that the mainframe system we were getting the data from was in fact malfunctioning. The simplicity of bit arrays makes confidence in their correctness very high - vs a searching approach for example.</p>\n'}, {'answer_id': 23532806, 'author': 'kendotwill', 'author_id': 1713375, 'author_profile': 'https://Stackoverflow.com/users/1713375', 'pm_score': 4, 'selected': False, 'text': '<p>Expanding on the <code>bitset</code> answer:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;bitset&gt;\n#include &lt;string&gt;\n\nusing namespace std;\nint main() {\n  bitset&lt;8&gt; byte(std::string("10010011");\n\n  // Set Bit\n  byte.set(3); // 10010111\n\n  // Clear Bit\n  byte.reset(2); // 10010101\n\n  // Toggle Bit\n  byte.flip(7); // 00010101\n\n  cout &lt;&lt; byte &lt;&lt; endl;\n\n  return 0;\n}\n</code></pre>\n'}, {'answer_id': 23888594, 'author': 'Vincet', 'author_id': 3679614, 'author_profile': 'https://Stackoverflow.com/users/3679614', 'pm_score': -1, 'selected': False, 'text': '<p>Try one of these functions in the C language to change n bit:</p>\n\n<pre><code>char bitfield;\n\n// Start at 0th position\n\nvoid chang_n_bit(int n, int value)\n{\n    bitfield = (bitfield | (1 &lt;&lt; n)) &amp; (~( (1 &lt;&lt; n) ^ (value &lt;&lt; n) ));\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>void chang_n_bit(int n, int value)\n{\n    bitfield = (bitfield | (1 &lt;&lt; n)) &amp; ((value &lt;&lt; n) | ((~0) ^ (1 &lt;&lt; n)));\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>void chang_n_bit(int n, int value)\n{\n    if(value)\n        bitfield |= 1 &lt;&lt; n;\n    else\n        bitfield &amp;= ~0 ^ (1 &lt;&lt; n);\n}\n\nchar get_n_bit(int n)\n{\n    return (bitfield &amp; (1 &lt;&lt; n)) ? 1 : 0;\n}\n</code></pre>\n'}, {'answer_id': 28376414, 'author': 'sam msft', 'author_id': 640259, 'author_profile': 'https://Stackoverflow.com/users/640259', 'pm_score': 3, 'selected': False, 'text': '<p>Here are some macros I use:</p>\n\n<pre><code>SET_FLAG(Status, Flag)            ((Status) |= (Flag))\nCLEAR_FLAG(Status, Flag)          ((Status) &amp;= ~(Flag))\nINVALID_FLAGS(ulFlags, ulAllowed) ((ulFlags) &amp; ~(ulAllowed))\nTEST_FLAGS(t,ulMask, ulBit)       (((t)&amp;(ulMask)) == (ulBit))\nIS_FLAG_SET(t,ulMask)             TEST_FLAGS(t,ulMask,ulMask)\nIS_FLAG_CLEAR(t,ulMask)           TEST_FLAGS(t,ulMask,0)\n</code></pre>\n'}, {'answer_id': 37488546, 'author': 'Jeegar Patel', 'author_id': 775964, 'author_profile': 'https://Stackoverflow.com/users/775964', 'pm_score': 4, 'selected': False, 'text': '<p>If you want to perform this all operation with C programming in the <strong>Linux kernel</strong> then I suggest to use standard APIs of the Linux kernel.</p>\n\n<p>See <a href="https://www.kernel.org/doc/htmldocs/kernel-api/ch02s03.html" rel="nofollow noreferrer">https://www.kernel.org/doc/htmldocs/kernel-api/ch02s03.html</a></p>\n\n<pre><code>set_bit  Atomically set a bit in memory\nclear_bit  Clears a bit in memory\nchange_bit  Toggle a bit in memory\ntest_and_set_bit  Set a bit and return its old value\ntest_and_clear_bit  Clear a bit and return its old value\ntest_and_change_bit  Change a bit and return its old value\ntest_bit  Determine whether a bit is set\n</code></pre>\n\n<p>Note: Here the whole operation happens in a single step. So these all are  guaranteed to be <strong>atomic</strong> even on SMP computers and are useful\nto keep coherence across processors.</p>\n'}, {'answer_id': 46454677, 'author': 'chux - Reinstate Monica', 'author_id': 2410359, 'author_profile': 'https://Stackoverflow.com/users/2410359', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>How do you set, clear, and toggle a single bit?</p>\n</blockquote>\n\n<p>To address a common coding pitfall when attempting to form the mask:<br>\n<strong><code>1</code> is not always wide enough</strong></p>\n\n<p>What problems happen when <code>number</code> is a wider type than <code>1</code>?<br>\n<code>x</code> may be too great for the shift <code>1 &lt;&lt; x</code> leading to <em>undefined behavior</em> (UB).  Even if <code>x</code> is not too great, <code>~</code> may not flip enough most-significant-bits.</p>\n\n<pre><code>// assume 32 bit int/unsigned\nunsigned long long number = foo();\n\nunsigned x = 40; \nnumber |= (1 &lt;&lt; x);  // UB\nnumber ^= (1 &lt;&lt; x);  // UB\nnumber &amp;= ~(1 &lt;&lt; x); // UB\n\nx = 10;\nnumber &amp;= ~(1 &lt;&lt; x); // Wrong mask, not wide enough\n</code></pre>\n\n<hr>\n\n<p><strong>To insure 1 is wide enough:</strong></p>\n\n<p>Code could use <code>1ull</code> or pedantically <code>(uintmax_t)1</code> and let the compiler optimize.</p>\n\n<pre><code>number |= (1ull &lt;&lt; x);\nnumber |= ((uintmax_t)1 &lt;&lt; x);\n</code></pre>\n\n<p>Or cast - which makes for coding/review/maintenance issues keeping the cast correct and up-to-date.</p>\n\n<pre><code>number |= (type_of_number)1 &lt;&lt; x;\n</code></pre>\n\n<p>Or gently promote the <code>1</code> by forcing a math operation that is as least as wide as the type of <code>number</code>.</p>\n\n<pre><code>number |= (number*0 + 1) &lt;&lt; x;\n</code></pre>\n\n<hr>\n\n<p>As with most bit manipulations, best to work with <em>unsigned</em> types rather than <em>signed</em> ones</p>\n'}, {'answer_id': 48725080, 'author': 'Joakim L. Christiansen', 'author_id': 4216153, 'author_profile': 'https://Stackoverflow.com/users/4216153', 'pm_score': 2, 'selected': False, 'text': '<p>A templated version (put in a header file) with support for changing multiple bits (works on AVR microcontrollers btw):</p>\n<pre class="lang-cpp prettyprint-override"><code>namespace bit {\n  template &lt;typename T1, typename T2&gt;\n  constexpr inline T1 bitmask(T2 bit) \n  {return (T1)1 &lt;&lt; bit;}\n  template &lt;typename T1, typename T3, typename ...T2&gt;\n  constexpr inline T1 bitmask(T3 bit, T2 ...bits) \n  {return ((T1)1 &lt;&lt; bit) | bitmask&lt;T1&gt;(bits...);}\n\n  /** Set these bits (others retain their state) */\n  template &lt;typename T1, typename ...T2&gt;\n  constexpr inline void set (T1 &amp;variable, T2 ...bits) \n  {variable |= bitmask&lt;T1&gt;(bits...);}\n  /** Set only these bits (others will be cleared) */\n  template &lt;typename T1, typename ...T2&gt;\n  constexpr inline void setOnly (T1 &amp;variable, T2 ...bits) \n  {variable = bitmask&lt;T1&gt;(bits...);}\n  /** Clear these bits (others retain their state) */\n  template &lt;typename T1, typename ...T2&gt;\n  constexpr inline void clear (T1 &amp;variable, T2 ...bits) \n  {variable &amp;= ~bitmask&lt;T1&gt;(bits...);}\n  /** Flip these bits (others retain their state) */\n  template &lt;typename T1, typename ...T2&gt;\n  constexpr inline void flip (T1 &amp;variable, T2 ...bits) \n  {variable ^= bitmask&lt;T1&gt;(bits...);}\n  /** Check if any of these bits are set */\n  template &lt;typename T1, typename ...T2&gt;\n  constexpr inline bool isAnySet(const T1 &amp;variable, T2 ...bits) \n  {return variable &amp; bitmask&lt;T1&gt;(bits...);}\n  /** Check if all these bits are set */\n  template &lt;typename T1, typename ...T2&gt;\n  constexpr inline bool isSet (const T1 &amp;variable, T2 ...bits) \n  {return ((variable &amp; bitmask&lt;T1&gt;(bits...)) == bitmask&lt;T1&gt;(bits...));}\n  /** Check if all these bits are not set */\n  template &lt;typename T1, typename ...T2&gt;\n  constexpr inline bool isNotSet (const T1 &amp;variable, T2 ...bits) \n  {return ((variable &amp; bitmask&lt;T1&gt;(bits...)) != bitmask&lt;T1&gt;(bits...));}\n}\n</code></pre>\n<p>Example of use:</p>\n<pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;\n#include &lt;bitset&gt; // for console output of binary values\n\n// and include the code above of course\n\nusing namespace std;\n\nint main() {\n  uint8_t v = 0b1111\'1100;\n  bit::set(v, 0);\n  cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n\n  bit::clear(v, 0,1);\n  cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n\n  bit::flip(v, 0,1);\n  cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n\n  bit::clear(v, 0,1,2,3,4,5,6,7);\n  cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n\n  bit::flip(v, 0,7);\n  cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n}\n</code></pre>\n<p>BTW: It turns out that constexpr and inline is not used if not sending the optimizer argument (e.g.: -O3) to the compiler. Feel free to try the code at <a href="https://godbolt.org/" rel="nofollow noreferrer">https://godbolt.org/</a> and look at the ASM output.</p>\n'}, {'answer_id': 48906086, 'author': 'Sazzad Hissain Khan', 'author_id': 1084174, 'author_profile': 'https://Stackoverflow.com/users/1084174', 'pm_score': 3, 'selected': False, 'text': '<pre><code>int set_nth_bit(int num, int n){    \n    return (num | 1 &lt;&lt; n);\n}\n\nint clear_nth_bit(int num, int n){    \n    return (num &amp; ~( 1 &lt;&lt; n));\n}\n\nint toggle_nth_bit(int num, int n){    \n    return num ^ (1 &lt;&lt; n);\n}\n\nint check_nth_bit(int num, int n){    \n    return num &amp; (1 &lt;&lt; n);\n}\n</code></pre>\n'}, {'answer_id': 56521123, 'author': 'Pankaj Prakash', 'author_id': 2401088, 'author_profile': 'https://Stackoverflow.com/users/2401088', 'pm_score': 5, 'selected': False, 'text': '<blockquote>\n  <p><strong>Let suppose few things first</strong><br>\n  <code>num = 55</code> Integer to perform bitwise operations (set, get, clear, toggle).<br>\n  <code>n = 4</code> 0 based bit position to perform bitwise operations.   </p>\n</blockquote>\n\n<h1>How to get a bit?</h1>\n\n<ol>\n<li>To get the <code>nth</code> bit of num right shift <code>num</code>, <code>n</code> times. Then perform bitwise AND <code>&amp;</code> with 1.</li>\n</ol>\n\n<pre><code>bit = (num &gt;&gt; n) &amp; 1;\n</code></pre>\n\n<p><strong>How it works?</strong></p>\n\n<pre><code>       0011 0111 (55 in decimal)\n    &gt;&gt;         4 (right shift 4 times)\n-----------------\n       0000 0011\n     &amp; 0000 0001 (1 in decimal)\n-----------------\n    =&gt; 0000 0001 (final result)\n</code></pre>\n\n<h1>How to set a bit?</h1>\n\n<ol>\n<li>To set a particular bit of number. Left shift 1 <code>n</code> times. Then perform bitwise OR <code>|</code> operation with <code>num</code>.</li>\n</ol>\n\n<pre><code>num |= (1 &lt;&lt; n);    // Equivalent to; num = (1 &lt;&lt; n) | num;\n</code></pre>\n\n<p><strong>How it works?</strong></p>\n\n<pre><code>       0000 0001 (1 in decimal)\n    &lt;&lt;         4 (left shift 4 times)\n-----------------\n       0001 0000\n     | 0011 0111 (55 in decimal)\n-----------------\n    =&gt; 0001 0000 (final result)\n</code></pre>\n\n<h1>How to clear a bit?</h1>\n\n<ol>\n<li>Left shift 1, <code>n</code> times i.e. <code>1 &lt;&lt; n</code>.</li>\n<li>Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e. <code>~ (1 &lt;&lt; n)</code>.</li>\n<li>Finally, perform bitwise AND <code>&amp;</code> operation with the above result and <code>num</code>. The above three steps together can be written as <code>num &amp; (~ (1 &lt;&lt; n))</code>;</li>\n</ol>\n\n<p><a href="https://i.stack.imgur.com/mf8hm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mf8hm.png" alt="Steps to clear a bit"></a></p>\n\n<pre><code>num &amp;= (~(1 &lt;&lt; n));    // Equivalent to; num = num &amp; (~(1 &lt;&lt; n));\n</code></pre>\n\n<p><strong>How it works?</strong></p>\n\n<pre><code>       0000 0001 (1 in decimal)\n    &lt;&lt;         4 (left shift 4 times)\n-----------------\n     ~ 0001 0000\n-----------------\n       1110 1111\n     &amp; 0011 0111 (55 in decimal)\n-----------------\n    =&gt; 0010 0111 (final result)\n</code></pre>\n\n<h1>How to toggle a bit?</h1>\n\n<p>To toggle a bit we use bitwise XOR <code>^</code> operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different, otherwise evaluates to 0.  </p>\n\n<p>Which means to toggle a bit, we need to perform XOR operation with the bit you want to toggle and 1. </p>\n\n<pre><code>num ^= (1 &lt;&lt; n);    // Equivalent to; num = num ^ (1 &lt;&lt; n);\n</code></pre>\n\n<p><strong>How it works?</strong> </p>\n\n<ul>\n<li>If the bit to toggle is 0 then, <code>0 ^ 1 =&gt; 1</code>.  </li>\n<li>If the bit to toggle is 1 then, <code>1 ^ 1 =&gt; 0</code>.</li>\n</ul>\n\n<pre><code>       0000 0001 (1 in decimal)\n    &lt;&lt;         4 (left shift 4 times)\n-----------------\n       0001 0000\n     ^ 0011 0111 (55 in decimal)\n-----------------\n    =&gt; 0010 0111 (final result)\n</code></pre>\n\n<p>Recommended reading - <a href="https://codeforwin.org/2016/01/bitwise-operator-programming-exercises-and-solutions-in-c.html" rel="noreferrer">Bitwise operator exercises</a></p>\n'}, {'answer_id': 61374583, 'author': 'Balaji Boggaram Ramanarayan', 'author_id': 2101290, 'author_profile': 'https://Stackoverflow.com/users/2101290', 'pm_score': 2, 'selected': False, 'text': "<p>This program is based out of @Jeremy's above solution. If someone wish to quickly play around.</p>\n\n<pre><code>public class BitwiseOperations {\n\n    public static void main(String args[]) {\n\n        setABit(0, 4); // set the 4th bit, 0000 -&gt; 1000 [8]\n        clearABit(16, 5); // clear the 5th bit, 10000 -&gt; 00000 [0]\n        toggleABit(8, 4); // toggle the 4th bit, 1000 -&gt; 0000 [0]\n        checkABit(8,4); // check the 4th bit 1000 -&gt; true \n    }\n\n    public static void setABit(int input, int n) {\n        input = input | ( 1 &lt;&lt; n-1);\n        System.out.println(input);\n    }\n\n\n    public static void clearABit(int input, int n) {\n        input = input &amp; ~(1 &lt;&lt; n-1);\n        System.out.println(input);\n    }\n\n    public static void toggleABit(int input, int n) {\n        input = input ^ (1 &lt;&lt; n-1);\n        System.out.println(input);\n    }\n\n    public static void checkABit(int input, int n) {\n        boolean isSet = ((input &gt;&gt; n-1) &amp; 1) == 1; \n        System.out.println(isSet);\n    }\n}\n\n\nOutput :\n8\n0\n0\ntrue\n</code></pre>\n"}, {'answer_id': 66075462, 'author': 'Dominic van der Zypen', 'author_id': 8082048, 'author_profile': 'https://Stackoverflow.com/users/8082048', 'pm_score': 0, 'selected': False, 'text': '<h1>Setting the nth bit to x (bit value) without using -1</h1>\n<p>Sometimes when you are not sure what -1 or the like will result in, you may wish to set the nth bit without using -1:</p>\n<pre><code>number = (((number | (1 &lt;&lt; n)) ^ (1 &lt;&lt; n))) | (x &lt;&lt; n);\n</code></pre>\n<p>Explanation: <code>((number | (1 &lt;&lt; n)</code> sets the nth bit to 1 (where <code>|</code> denotes bitwise OR), then with <code>(...) ^ (1 &lt;&lt; n)</code> we set the nth bit to 0, and finally with <code>(...) | x &lt;&lt; n)</code> we set the nth bit that was 0, to (bit value) <code>x</code>.</p>\n<p>This also works in <code>golang</code>.</p>\n'}, {'answer_id': 66667330, 'author': 'lckid2004', 'author_id': 15412355, 'author_profile': 'https://Stackoverflow.com/users/15412355', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a routine in C to perform the basic bitwise operations:</p>\n<pre><code>#define INT_BIT (unsigned int) (sizeof(unsigned int) * 8U) //number of bits in unsigned int\n\nint main(void)\n{\n    \n    unsigned int k = 5; //k is the bit position; here it is the 5th bit from the LSb (0th bit)\n    \n    unsigned int regA = 0x00007C7C; //we perform bitwise operations on regA\n    \n    regA |= (1U &lt;&lt; k);    //Set kth bit\n    \n    regA &amp;= ~(1U &lt;&lt; k);   //Clear kth bit\n    \n    regA ^= (1U &lt;&lt; k);    //Toggle kth bit\n    \n    regA = (regA &lt;&lt; k) | regA &gt;&gt; (INT_BIT - k); //Rotate left by k bits\n    \n    regA = (regA &gt;&gt; k) | regA &lt;&lt; (INT_BIT - k); //Rotate right by k bits\n\n    return 0;   \n}\n\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/47981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445087/']