By JeffV

2008-09-07 00:42:17 8 Comments

How do you set, clear, and toggle a bit?


@user20000 2020-08-06 20:40:13

Example of setting bit 16.

#include <stdio.h>
#define SET_BIT_NUMBER 16

int main() {

   unsigned int dataWord = 0;

   dataWord |= (1 << SET_BIT_NUMBER);
   printf("dataWord (hex): %x\n", dataWord);

   return 0;

@Costantino Grana 2020-08-06 23:21:25

This is not a proper answer. You need to put some effort and explain. Moreover the question was how to set, clear and toggle a bit. You are only setting.

@Balaji Boggaram Ramanarayan 2020-04-22 20:30:38

This program is based out of @Jeremy's above solution. If someone wish to quickly play around.

public class BitwiseOperations {

    public static void main(String args[]) {

        setABit(0, 4); // set the 4th bit, 0000 -> 1000 [8]
        clearABit(16, 5); // clear the 5th bit, 10000 -> 00000 [0]
        toggleABit(8, 4); // toggle the 4th bit, 1000 -> 0000 [0]
        checkABit(8,4); // check the 4th bit 1000 -> true 

    public static void setABit(int input, int n) {
        input = input | ( 1 << n-1);

    public static void clearABit(int input, int n) {
        input = input & ~(1 << n-1);

    public static void toggleABit(int input, int n) {
        input = input ^ (1 << n-1);

    public static void checkABit(int input, int n) {
        boolean isSet = ((input >> n-1) & 1) == 1; 

Output :

@user1899861 2012-12-30 02:31:33

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 sizeof() operator works properly.

bool    IsGph[256], IsNotGph[256];

//  Initialize boolean array to detect printable characters
for(i=0; i<sizeof(IsGph); i++)  {
    IsGph[i] = isgraph((unsigned char)i);

So, to your question, IsGph[i] =1, or IsGph[i] =0 make setting and clearing bools easy.

To find unprintable characters:

//  Initialize boolean array to detect UN-printable characters, 
//  then call function to toggle required bits true, while initializing a 2nd
//  boolean array as the complement of the 1st.
for(i=0; i<sizeof(IsGph); i++)  {
    if(IsGph[i])    {
         IsNotGph[i] = 0;
    }   else   {
         IsNotGph[i] = 1;

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.

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.

@galinette 2014-11-17 20:03:37

std::bitset is indeed implemented as bits by most compilers

@user1899861 2014-11-17 21:08:22

@galinette, Agreed. The header file #include <bitset> is a good resource in this regard. Also, the special class vector<bool> for when you need the size of the vector to change. The C++ STL, 2nd Edition, Nicolai M. Josuttis covers them exhaustively on pgs 650 and 281 respectively. C++11 adds a few new capabilities to std::bitset, of special interest to me is a hash function in unordered containers. Thanks for the heads up! I'm going to delete my brain-cramp comment. Already enough garbage out on the web. I don't want to add to it.

@M.M 2015-02-06 23:55:27

This uses at least a whole byte of storage for each bool. Maybe even 4 bytes for C89 setups that use int to implement bool

@user1899861 2015-02-12 07:23:47

@MattMcNabb, you are correct. In C++ the size of the int type necessary to implement a boolean is not specified by the standard. I realized this answer was in error some time ago, but decided to leave it here as people are apparently finding it useful. For those wanting to use bits galinette's comment is most helpful as is my bit library here ...

@Ben Voigt 2015-02-22 02:20:04

@RocketRoy: Probably worth changing the sentence that claims this is an example of "bit operations", then.

@Pankaj Prakash 2019-06-10 05:52:54

Let suppose few things first
num = 55 Integer to perform bitwise operations (set, get, clear, toggle).
n = 4 0 based bit position to perform bitwise operations.

How to get a bit?

  1. To get the nth bit of num right shift num, n times. Then perform bitwise AND & with 1.
bit = (num >> n) & 1;

How it works?

       0011 0111 (55 in decimal)
    >>         4 (right shift 4 times)
       0000 0011
     & 0000 0001 (1 in decimal)
    => 0000 0001 (final result)

How to set a bit?

  1. To set a particular bit of number. Left shift 1 n times. Then perform bitwise OR | operation with num.
num |= (1 << n);    // Equivalent to; num = (1 << n) | num;

How it works?

       0000 0001 (1 in decimal)
    <<         4 (left shift 4 times)
       0001 0000
     | 0011 0111 (55 in decimal)
    => 0001 0000 (final result)

How to clear a bit?

  1. Left shift 1, n times i.e. 1 << n.
  2. Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e. ~ (1 << n).
  3. Finally, perform bitwise AND & operation with the above result and num. The above three steps together can be written as num & (~ (1 << n));

Steps to clear a bit

num &= (~(1 << n));    // Equivalent to; num = num & (~(1 << n));

How it works?

       0000 0001 (1 in decimal)
    <<         4 (left shift 4 times)
     ~ 0001 0000
       1110 1111
     & 0011 0111 (55 in decimal)
    => 0010 0111 (final result)

How to toggle a bit?

To toggle a bit we use bitwise XOR ^ operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different, otherwise evaluates to 0.

Which means to toggle a bit, we need to perform XOR operation with the bit you want to toggle and 1.

num ^= (1 << n);    // Equivalent to; num = num ^ (1 << n);

How it works?

  • If the bit to toggle is 0 then, 0 ^ 1 => 1.
  • If the bit to toggle is 1 then, 1 ^ 1 => 0.
       0000 0001 (1 in decimal)
    <<         4 (left shift 4 times)
       0001 0000
     ^ 0011 0111 (55 in decimal)
    => 0010 0111 (final result)

Recommended reading - Bitwise operator exercises

@Chandra Shekhar 2019-12-28 18:37:41

Thanks for the detailed explanation. Here is the link for practice problem for BIT Magic link

@Sazzad Hissain Khan 2018-02-21 12:35:12

int set_nth_bit(int num, int n){    
    return (num | 1 << n);

int clear_nth_bit(int num, int n){    
    return (num & ~( 1 << n));

int toggle_nth_bit(int num, int n){    
    return num ^ (1 << n);

int check_nth_bit(int num, int n){    
    return num & (1 << n);

@Xeverous 2020-05-05 16:07:23

Return type of check_nth_bit can be bool.

@Sazzad Hissain Khan 2020-05-05 18:09:52

@Xeverous yes it depends on callers intention

@yogeesh 2008-09-17 02:04:12

From's bitops.h:

**  Bit set, clear, and test operations
**  public domain snippet by Bob Stout

typedef enum {ERROR = -1, FALSE, TRUE} LOGICAL;

#define BOOL(x) (!(!(x)))

#define BitSet(arg,posn) ((arg) | (1L << (posn)))
#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))
#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))
#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))

OK, let's analyze things...

The common expression that you seem to be having problems with in all of these is "(1L << (posn))". All this does is create a mask with a single bit on and which will work with any integer type. The "posn" argument specifies the position where you want the bit. If posn==0, then this expression will evaluate to:

0000 0000 0000 0000 0000 0000 0000 0001 binary.

If posn==8, it will evaluate to:

0000 0000 0000 0000 0000 0001 0000 0000 binary.

In other words, it simply creates a field of 0's with a 1 at the specified position. The only tricky part is in the BitClr() macro where we need to set a single 0 bit in a field of 1's. This is accomplished by using the 1's complement of the same expression as denoted by the tilde (~) operator.

Once the mask is created it's applied to the argument just as you suggest, by use of the bitwise and (&), or (|), and xor (^) operators. Since the mask is of type long, the macros will work just as well on char's, short's, int's, or long's.

The bottom line is that this is a general solution to an entire class of problems. It is, of course, possible and even appropriate to rewrite the equivalent of any of these macros with explicit mask values every time you need one, but why do it? Remember, the macro substitution occurs in the preprocessor and so the generated code will reflect the fact that the values are considered constant by the compiler - i.e. it's just as efficient to use the generalized macros as to "reinvent the wheel" every time you need to do bit manipulation.

Unconvinced? Here's some test code - I used Watcom C with full optimization and without using _cdecl so the resulting disassembly would be as clean as possible:

----[ TEST.C ]----------------------------------------------------------------

#define BOOL(x) (!(!(x)))

#define BitSet(arg,posn) ((arg) | (1L << (posn)))
#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))
#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))
#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))

int bitmanip(int word)
      word = BitSet(word, 2);
      word = BitSet(word, 7);
      word = BitClr(word, 3);
      word = BitFlp(word, 9);
      return word;

----[ TEST.OUT (disassembled) ]-----------------------------------------------

Module: C:\BINK\tst.c

Segment: _TEXT  BYTE   00000008 bytes  
 0000  0c 84             bitmanip_       or      al,84H    ; set bits 2 and 7
 0002  80 f4 02                          xor     ah,02H    ; flip bit 9 of EAX (bit 1 of AH)
 0005  24 f7                             and     al,0f7H
 0007  c3                                ret     

No disassembly errors

----[ finis ]-----------------------------------------------------------------

@Dan 2008-10-18 01:51:34

2 things about this: (1) in perusing your macros, some may incorrectly believe that the macros actually set/clear/flip bits in the arg, however there is no assignment; (2) your test.c is not complete; I suspect if you ran more cases you'd find a problem (reader exercise)

@Lundin 2011-08-18 19:14:17

-1 This is just weird obfuscation. Never re-invent the C language by hiding away language syntax behind macros, it is very bad practice. Then some oddities: first, 1L is signed, meaning all bit operations will be performed on a signed type. Everything passed to these macros will return as signed long. Not good. Second, this will work very inefficiently on smaller CPUs as it enforces long when the operations could have been on int level. Third, function-like macros are the root of all evil: you have no type safety whatsoever. Also, the previous comment about no assignment is very valid.

@M.M 2015-02-06 23:51:47

This will fail if arg is long long. 1L needs to be the widest possible type, so (uintmax_t)1 . (You might get away with 1ull)

@Peter Cordes 2017-11-10 21:38:16

Did you optimize for code-size? On Intel mainstream CPUs you'll get partial-register stalls when reading AX or EAX after this function returns, because it writes the 8-bit components of EAX. (It's fine on AMD CPUs, or others that don't rename partial registers separately from the full register. Haswell/Skylake don't rename AL separately, but they do rename AH.).

@Jeet Parikh 2018-07-11 17:32:56

Variable used

int value, pos;

value - Data
pos - position of the bit that we're interested to set, clear or toggle.

Set a bit:

value = value | 1 << pos;

Clear a bit:

value = value & ~(1 << pos); 

Toggle a bit:

value = value ^ 1 << pos;

@Jeremy Ruten 2008-09-07 00:50:45

Setting a bit

Use the bitwise OR operator (|) to set a bit.

number |= 1UL << n;

That will set the nth bit of number. n should be zero, if you want to set the 1st bit and so on upto n-1, if you want to set the nth bit.

Use 1ULL if number is wider than unsigned long; promotion of 1UL << n doesn't happen until after evaluating 1UL << n where it's undefined behaviour to shift by more than the width of a long. The same applies to all the rest of the examples.

Clearing a bit

Use the bitwise AND operator (&) to clear a bit.

number &= ~(1UL << n);

That will clear the nth bit of number. You must invert the bit string with the bitwise NOT operator (~), then AND it.

Toggling a bit

The XOR operator (^) can be used to toggle a bit.

number ^= 1UL << n;

That will toggle the nth bit of number.

Checking a bit

You didn't ask for this, but I might as well add it.

To check a bit, shift the number n to the right, then bitwise AND it:

bit = (number >> n) & 1U;

That will put the value of the nth bit of number into the variable bit.

Changing the nth bit to x

Setting the nth bit to either 1 or 0 can be achieved with the following on a 2's complement C++ implementation:

number ^= (-x ^ number) & (1UL << n);

Bit n will be set if x is 1, and cleared if x is 0. If x has some other value, you get garbage. x = !!x will booleanize it to 0 or 1.

To make this independent of 2's complement negation behaviour (where -1 has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.

number ^= (-(unsigned long)x ^ number) & (1UL << n);


unsigned long newbit = !!x;    // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);

It's generally a good idea to use unsigned types for portable bit manipulation.


number = (number & ~(1UL << n)) | (x << n);

(number & ~(1UL << n)) will clear the nth bit and (x << n) will set the nth bit to x.

It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like the community wiki answer further down) or some sort of encapsulation.

@Aaron 2008-09-17 17:13:35

I would like to note that on platforms that have native support for bit set/clear (ex, AVR microcontrollers), compilers will often translate 'myByte |= (1 << x)' into the native bit set/clear instructions whenever x is a constant, ex: (1 << 5), or const unsigned x = 5.

@Chris Young 2008-11-16 07:49:52

bit = number & (1 << x); will not put the value of bit x into bit unless bit has type _Bool (<stdbool.h>). Otherwise, bit = !!(number & (1 << x)); will..

@John Zwinck 2009-01-03 22:55:23

These sorts of solutions only work when the target variable is of an integral type. More general solutions can be made to work on other useful target types, such as arrays.

@Happy Green Kid Naps 2013-05-09 14:27:23

It's just me, but I'd prefer to parenthesize the bit shift expressions (similar to what @Aaron has done above).

@anatolyg 2013-05-09 15:58:03

BTW the bit-fiddling here will silently fail if number is wider than int

@aaronman 2013-06-26 18:47:45

why don't you change the last one to bit = (number >> x) & 1

@phuclv 2013-08-01 02:04:20

@Aaron: x86 has native bit test and set/clear/complement instructions too

@user2568508 2013-09-13 21:40:25

I think there is a problem in the notation. Say I have 0011 (decimal 3) and I want to check if second bit is set, e.g., the one in bold: 0 0 1 1. How do you refer to x? Will it be 2nd or 1st bit according to your notation, because if it is 2nd bit, I think you suggestion won't work, e.g., since you will shift 1 two times, and get 100 - which won't yield 2nd bit as I defined above. Isn't it?

@Siyuan Ren 2013-12-10 08:53:35

1 is an int literal, which is signed. So all the operations here operate on signed numbers, which is not well defined by the standards. The standards does not guarantee two's complement or arithmetic shift so it is better to use 1U.

@JonS 2014-07-07 22:46:18

To clarify anatolyg's comment, the constant "1" with no modifiers is defined to be a signed int. To have this work properly for all variables, use "1ULL" instead.

@M.M 2015-02-06 23:48:45

@JonS for all variables up to unsigned long long in size anyway... there may be implementation-defined extensions such as __int128 . To be ultra-safe (uintmax_t)1 << x

@jiasli 2015-03-24 00:38:31

I prefer number = number & ~(1 << n) | (x << n); for Changing the n-th bit to x.

@chqrlie 2015-03-24 08:48:09

@Jiashuo Li: this statement will fail if number is larger than int and n is greater or equal to the number of bits in an int. It even invokes undefined behaviour in this case. number = number & ~((uintmax_t)1 << n) | ((uintmax_t)x << n); is a generic expression that should work for all sizes of number but may generate ugly and inefficient code for smaller sizes.

@Anonymous 2015-04-08 11:28:40

Related to checking a bit: Why not simply use "number & 0x01" for checking the first bit, "number & 0x08" for the fourth etc. Imho more beautiful.

@Kevin 2016-01-18 18:04:45

Using operations like -x is not safe since the C standard allows signed integers to be (e.g.) sign-magnitude, ones' complement, or any other system that can express the necessary range, meaning that -x is not required to be the same as (~x) + 1. This isn't that big of a deal on modern architectures, but you never know what a sufficiently clever optimizing compiler will do with your code.

@71GA 2017-01-30 07:12:56

Why do we use ~ instead ! ?

@mckenzm 2017-03-09 02:19:49

@Anonymous. We use masks anyway so that if we ever need to do more than one extension is obvious ? Side note, uppercase/lowercase in EBCDIC is 1 bit.

@Patrick Roberts 2017-06-14 21:46:51

Doesn't the last example assume twos-complement representation? Isn't that bad / non-portable, whatever you want to call it?

@Adrian McCarthy 2017-09-05 20:34:55

@71GA: Bitwise negation (~) inverts all the bits, so ~0xFFF0FFFF is 0x000F0000. Boolean not (!) gives 0 if the value is non-zero or 1 if the value is zero, so !0xFFF0FFFF is 0x00000000.

@Peter Cordes 2017-11-10 19:55:19

@PatrickRoberts: Yes, it does require 2's complement. In one's complement, -1 is 0b1111..1110. (All-ones is -0). C++ also allows sign/magnitude integer representations, where -x just flips the sign bit. I updated this answer to point that out. It's totally fine if you are only targeting 2's complement C++ implementations. It's not UB, it's merely implementation-defined, so it is required to work correctly on implementations the define signed integers as 2's complement. I also changed the constants to 1UL, with a note that 1ULL may be required.

@Peter Cordes 2017-11-10 19:57:07

@Kevin: It is guaranteed to be safe on a C++ implementation that uses 2's complement. It's "implementation defined", not UB. The thing to worry about is portability to one's complement or sign/magnitude, not optimizing compilers.

@Kevin 2017-11-10 20:55:24

@Peter -x is UB if x is INT_MIN.

@Peter Cordes 2017-11-10 21:05:27

@Kevin: oh right, should be -(unsigned long)x which would also sidestep the signed-integer representation. (unsigned base 2 matches 2's complement semantics.) But it only works correctly if x is 0 or 1. Remember we're setting bit n to x.

@Kevin 2017-11-10 21:18:53

@PeterCordes: That's entirely reasonable. But when a developer tells me "this invariant will always hold!" I get real nervous.

@Peter Cordes 2017-11-10 21:21:46

@Kevin: I decided to leave out any mention of signed-overflow UB in my last edit, because you want to use unsigned anyway for portable 0U - 1U -> all-ones. How does it look now? I tried to keep the answer simple. I did mention that you may need to booleanize with !!x. If this was my own answer, I might insert more text about always using unsigned, but I'm just maintaining this old canonical answer. (Jeremy, hope you like the changes, you might want to edit to put my changes into your own words or whatever else you want to say nearly 9 years later.)

@Peter Cordes 2017-11-10 21:26:00

Just noticed in the edit history that the changing nth bit to x section was added by another 3rd-party edit, and wasn't Jeremy's work in the first place.

@EM-Creations 2018-04-17 08:07:34

Is the checking of a bit in your example destructive?

@maksadbek 2019-11-19 16:45:58

Why not to use a number = number | (x << n) & (1 << n)) for changing nth bit to x ?

@avivgood2 2020-04-22 08:37:49

Is you method of Changing the nth bit to x valid for C90 as well? And is this answered valid for unsigned numbers as well?

@Steve Karg 2008-11-04 22:35:47

I use macros defined in a header file to handle bit set and clear:

/* a=target variable, b=bit number to act upon 0-n */
#define BIT_SET(a,b) ((a) |= (1ULL<<(b)))
#define BIT_CLEAR(a,b) ((a) &= ~(1ULL<<(b)))
#define BIT_FLIP(a,b) ((a) ^= (1ULL<<(b)))
#define BIT_CHECK(a,b) (!!((a) & (1ULL<<(b))))        // '!!' to make sure this returns 0 or 1

/* x=target variable, y=mask */
#define BITMASK_SET(x,y) ((x) |= (y))
#define BITMASK_CLEAR(x,y) ((x) &= (~(y)))
#define BITMASK_FLIP(x,y) ((x) ^= (y))
#define BITMASK_CHECK_ALL(x,y) (((x) & (y)) == (y))   // warning: evaluates y twice
#define BITMASK_CHECK_ANY(x,y) ((x) & (y))

@Robert Kelly 2013-10-02 14:53:25

Uh I realize this is a 5 year old post but there is no argument duplication in any of those macros, Dan

@brigadir 2014-12-11 12:00:52

BITMASK_CHECK(x,y) ((x) & (y)) must be ((x) & (y)) == (y) otherwise it returns incorrect result on multibit mask (ex. 5 vs. 3) /*Hello to all gravediggers :)*/

@M.M 2015-02-06 23:50:06

1 should be (uintmax_t)1 or similar in case anybody tries to use these macros on a long or larger type

@Peter Cordes 2017-11-10 21:27:00

Or 1ULL works as well as (uintmax_t) on most implementations.

@Peter Cordes 2017-11-10 21:31:02

@brigadir: depends whether you want to check for any bits set or all bits set. I updated the answer to include both with descriptive names.

@Handy999 2018-11-20 09:24:42

BITMASK_CHECK_ALL(x,y) can be implemented as !~((~(y))|(x))

@Tavian Barnes 2019-08-13 20:14:54

@Handy999 It's a bit easier to see why that works after applying De Morgan's law and re-arranging to get !(~(x) & (y))

@nsanders 2008-09-07 00:45:38

Use the bitwise operators: & |

To set last bit in 000b:

foo = foo | 001b

To check last bit in foo:

if ( foo & 001b ) ....

To clear last bit in foo:

foo = foo & 110b

I used XXXb for clarity. You'll probably be working with HEX representation, depending on the data structure in which you're packing bits.

@Lundin 2015-12-14 09:14:50

There is no binary notation in C. Binary integer constants is a non-standard extension.

@Peter L 2019-10-29 17:54:47

Use XOR to toggle a bit: foo = foo ^ MY_MASK

@Peter L 2019-10-29 17:57:45

Use NOT to invert a mask to do clear: foo = foo & ~MY_MASK

@Joakim L. Christiansen 2018-02-10 20:07:16

A C++11 templated version (put in a header):

namespace bit {
    template <typename T1, typename T2> inline void set  (T1 &variable, T2 bit) {variable |=  ((T1)1 << bit);}
    template <typename T1, typename T2> inline void clear(T1 &variable, T2 bit) {variable &= ~((T1)1 << bit);}
    template <typename T1, typename T2> inline void flip (T1 &variable, T2 bit) {variable ^=  ((T1)1 << bit);}
    template <typename T1, typename T2> inline bool test (T1 &variable, T2 bit) {return variable & ((T1)1 << bit);}

namespace bitmask {
    template <typename T1, typename T2> inline void set  (T1 &variable, T2 bits) {variable |= bits;}
    template <typename T1, typename T2> inline void clear(T1 &variable, T2 bits) {variable &= ~bits;}
    template <typename T1, typename T2> inline void flip (T1 &variable, T2 bits) {variable ^= bits;}
    template <typename T1, typename T2> inline bool test_all(T1 &variable, T2 bits) {return ((variable & bits) == bits);}
    template <typename T1, typename T2> inline bool test_any(T1 &variable, T2 bits) {return variable & bits;}

@melpomene 2018-02-10 20:11:47

This code is broken. (Also, why do you have ; after your function definitions?)

@Joakim L. Christiansen 2018-02-25 15:51:11

@melpomene The code is not broken, I did test it. Do you mean that it will not compile or that the result is wrong? About the extra ';' I don't remember, those can be removed indeed.

@melpomene 2018-02-25 18:25:33

(variable & bits == bits)?

@Joakim L. Christiansen 2018-02-27 20:56:01

Thank you for noticing, it was supposed to be ((variable & bits) == bits)

@pqnet 2019-10-25 20:27:22

use std::bitsetin c++11

@Asteroids With Wings 2020-04-22 16:53:12

Unfortunately you can't even see the code without scrolling sideways, as it's so verbose. Perhaps a few newlines would help?

@Vincet 2014-05-27 11:46:39

Try one of these functions in the C language to change n bit:

char bitfield;

// Start at 0th position

void chang_n_bit(int n, int value)
    bitfield = (bitfield | (1 << n)) & (~( (1 << n) ^ (value << n) ));


void chang_n_bit(int n, int value)
    bitfield = (bitfield | (1 << n)) & ((value << n) | ((~0) ^ (1 << n)));


void chang_n_bit(int n, int value)
        bitfield |= 1 << n;
        bitfield &= ~0 ^ (1 << n);

char get_n_bit(int n)
    return (bitfield & (1 << n)) ? 1 : 0;

@M.M 2015-02-06 23:57:15

value << n may cause undefined behaviour

@Martin York 2008-09-18 00:34:51

Using the Standard C++ Library: std::bitset<N>.

Or the Boost version: boost::dynamic_bitset.

There is no need to roll your own:

#include <bitset>
#include <iostream>

int main()
    std::bitset<5> x;

    x[1] = 1;
    x[2] = 0;
    // Note x[0-4]  valid

    std::cout << x << std::endl;

[Alpha:] > ./a.out

The Boost version allows a runtime sized bitset compared with a standard library compile-time sized bitset.

@paercebal 2008-09-19 18:16:50

+1. Not that std::bitset is usable from "C", but as the author tagged his/her question with "C++", AFAIK, your answer is the best around here... std::vector<bool> is another way, if one knows its pros and its cons

@xtofl 2008-09-27 19:21:57

Nice one, Martin! You can even use an enum to 'index' the bits: enum { cEngineOn, cDoorsOpen, cAircoOn }; std::bitset< cNBBITS > mybits; mybits[ cEngineOn ].set(); const bool cbDoorOpen = mybits[ cDoorsOpen ]; ...

@moogs 2008-10-15 11:43:55

among the answers here, i think this is the best way to manage bits...but I guess the spirit of the question was how to manipulate bits manually. still, +vote :)

@andrewdotnich 2008-11-13 06:10:19

@paercebal: vector<bool> isn't very efficient, as bool in C++ takes up a full byte of space, instead of 1 bit…

@Niklas 2008-12-12 20:40:15

@andrewdotnich: vector<bool> is (unfortunately) a specialization that stores the values as bits. See for more info...

@Lundin 2011-08-18 19:47:06

Maybe nobody mentioned it because this was tagged embedded. In most embedded systems you avoid STL like the plague. And boost support is likely a very rare bird to spot among most embedded compilers.

@Martin York 2011-08-18 19:51:34

@Lundin: Point one not true (some things in the STL are avoided, but a blanket statement like that is just to general, std::bitset is fine and cost nothing to use.). Point two Boost::dynamic_bitset does not depend on anything and can easily be used.

@Lundin 2011-08-19 06:26:06

@Martin It is very true. Besides specific performance killers like STL and templates, many embedded systems even avoid the whole standard libraries entirely, because they are such a pain to verify. Most of the embedded branch is embracing standards like MISRA, that requires static code analysis tools (any software professionals should be using such tools btw, not just embedded folks). Generally people have better things to do than run static analysis through the whole standard library - if its source code is even available to them on the specific compiler.

@Martin York 2011-08-19 06:41:32

@Lundin: Your statements are excessively broad (thus useless to argue about). I am sure that I can find situations were they are true. This does not change my initial point. Both of these classes are perfectly fine for use in embedded systems (and I know for a fact that they are used). Your initial point about STL/Boost not being used on embedded systems is also wrong. I am sure there are systems that don't use them and even the systems that do use them they are used judiciously but saying they are not used is just not correct (because there are systems were they are used).

@Martin York 2013-04-23 21:13:58

@jons34yp: The SGI documentation is more conical and generally has less mistakes than cppreference.

@mloskot 2013-09-10 12:24:02

The topic clearly states C language, not C++. Clearly, this is incorrect answer, so how on earth it received 120+ upvotes?!

@Martin York 2013-09-10 21:42:40

@mloskot: The question clearly states C++. Its in the tag below the question what languages are valid. It got 120+ up-votes because people who can read read the question and correctly evaluated in the context of the tags. :-) Ohh. And it is simple.

@mloskot 2013-09-11 09:14:15

@LokiAstari I dare to claim either the tag is incorrect or the topic and body is impreciese. This is important issue, as it leads to SO questions become vague, thus useless really.

@sudo 2014-08-13 07:14:23

All I know is that every single time I try to compile something made in C++, Boost becomes my new worst enemy. Still up-voted anyway.

@Martin York 2014-08-13 09:09:37

@9000: Why? You should not be doing anything with boost. This is a header only library and installing boost should be package management things sudo apt-get install boost-devel

@Luis Colorado 2014-09-30 10:53:38

The question asked for C/C++, so to be compliant with both world I think STL is not applicable here.

@Martin York 2014-09-30 14:47:02

@LuisColorado: Yet not to talk about it would mean not having the information available for users. The point is not limit your answer but to provide a solution. The OP will decide if it is relevant by putting a tick mark by the best answer. You vote up if you think it is an answer that is useful to the community or down if it has no value to the community.

@Martin York 2014-10-02 17:55:02

@LuisColorado: I disagree. It solved the problem in a way that others had not mentioned. Admittedly it was for a subset of people that used C++ but the question was tagged as C++ and thus a valid answer.

@Luis Colorado 2014-10-05 10:18:54

@LokiAstari, and that's the reason i just made a comment, no downvote, nothing else... just a comment.

@Peter - Reinstate Monica 2020-01-22 17:15:22

@MartinYork The embedded world is wide; but if the STL is avoided and instead some containers etc. are self-written the code is almost certainly less performant and contains more bugs. (I was working on one such system in the early 2000s. It was embedded alright, infotainment, but had the resources of a PC 5 years before.)

@Martin York 2020-01-22 19:04:04

@Peter-ReinstateMonica we are talking explicitly about the std::bitset only here.

@Peter - Reinstate Monica 2020-01-22 20:13:33

@MartinYork I was trying to support your statement; " STL/Boost not being used on embedded systems is also wrong" is correct. It is used. (And sometimes, when the system is sufficiently capable and the software is sufficiently complex it is actually a mistake not to use the STL because the alternatives -- no generics, or home-grown -- are worse.)

@Tim Ring 2008-09-17 14:10:22

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).

const unsigned char TQuickByteMask[8] =
   0x01, 0x02, 0x04, 0x08,
   0x10, 0x20, 0x40, 0x80,

/** Set bit in any sized bit mask.
 * @return    none
 * @param     bit    - Bit number.
 * @param     bitmap - Pointer to bitmap.
void TSetBit( short bit, unsigned char *bitmap)
    short n, x;

    x = bit / 8;        // Index to byte.
    n = bit % 8;        // Specific bit in byte.

    bitmap[x] |= TQuickByteMask[n];        // Set bit.

/** Reset bit in any sized mask.
 * @return  None
 * @param   bit    - Bit number.
 * @param   bitmap - Pointer to bitmap.
void TResetBit( short bit, unsigned char *bitmap)
    short n, x;

    x = bit / 8;        // Index to byte.
    n = bit % 8;        // Specific bit in byte.

    bitmap[x] &= (~TQuickByteMask[n]);    // Reset bit.

/** Toggle bit in any sized bit mask.
 * @return   none
 * @param   bit    - Bit number.
 * @param   bitmap - Pointer to bitmap.
void TToggleBit( short bit, unsigned char *bitmap)
    short n, x;

    x = bit / 8;        // Index to byte.
    n = bit % 8;        // Specific bit in byte.

    bitmap[x] ^= TQuickByteMask[n];        // Toggle bit.

/** Checks specified bit.
 * @return  1 if bit set else 0.
 * @param   bit    - Bit number.
 * @param   bitmap - Pointer to bitmap.
short TIsBitSet( short bit, const unsigned char *bitmap)
    short n, x;

    x = bit / 8;    // Index to byte.
    n = bit % 8;    // Specific bit in byte.

    // Test bit (logigal AND).
    if (bitmap[x] & TQuickByteMask[n])
        return 1;

    return 0;

/** Checks specified bit.
 * @return  1 if bit reset else 0.
 * @param   bit    - Bit number.
 * @param   bitmap - Pointer to bitmap.
short TIsBitReset( short bit, const unsigned char *bitmap)
    return TIsBitSet(bit, bitmap) ^ 1;

/** Count number of bits set in a bitmap.
 * @return   Number of bits set.
 * @param    bitmap - Pointer to bitmap.
 * @param    size   - Bitmap size (in bits).
 * @note    Not very efficient in terms of execution speed. If you are doing
 *        some computationally intense stuff you may need a more complex
 *        implementation which would be faster (especially for big bitmaps).
 *        See (
int TCountBits( const unsigned char *bitmap, int size)
    int i, count = 0;

    for (i=0; i<size; i++)
        if (TIsBitSet(i, bitmap))

    return count;

Note, to set bit 'n' in a 16 bit integer you do the following:

TSetBit( n, &my_int);

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...).

@R.. GitHub STOP HELPING ICE 2010-06-28 06:24:57

Don't use a table for a function that can be implemented with a single operator. TQuickByteMask[n] is equivalent to (1<<n). Also, making your arguments short is a very bad idea. The / and % will actually be a division, not bitshift/bitwise and, because signed division by a power of 2 cannot be implemented bitwise. You should make the argument type unsigned int!

@Lundin 2011-08-18 19:32:14

What's the point with this? It only makes the code slower and harder to read? I can't see a single advantage with it. 1u << n is easier to read for C programmers, and can hopefully be translated into a single clock tick CPU instruction. Your division on the other hand, will be translated to something around 10 ticks, or even as bad as up to 100 ticks, depending on how poorly the specific architecture handles division. As for the bitmap feature, it would make more sense to have a lookup table translating each bit index to a byte index, to optimize for speed.

@Lundin 2011-08-18 19:42:44

As for big/little endian, big endian will map integers and raw data (for example strings) in the same way: left-to-right msb to lsb throughout the whole bitmap. While little endian will map integers left to right as 7-0, 15-8, 23-18, 31-24, but raw data is still left-to-right msb to lsb. So how little endian is better for your particular algorithm is completely beyond me, it seems to be the opposite.

@jeb 2011-11-18 11:28:14

@R.. A table can be useful if your plattform can't shift efficiently, like old microchip mcu's, but of course then the division in the sample is absolutly inefficient

@Jeegar Patel 2016-05-27 16:41:15

If you want to perform this all operation with C programming in the Linux kernel then I suggest to use standard APIs of the Linux kernel.


set_bit  Atomically set a bit in memory
clear_bit  Clears a bit in memory
change_bit  Toggle a bit in memory
test_and_set_bit  Set a bit and return its old value
test_and_clear_bit  Clear a bit and return its old value
test_and_change_bit  Change a bit and return its old value
test_bit  Determine whether a bit is set

Note: Here the whole operation happens in a single step. So these all are guaranteed to be atomic even on SMP computers and are useful to keep coherence across processors.

@chux - Reinstate Monica 2017-09-27 18:18:48

How do you set, clear, and toggle a single bit?

To address a common coding pitfall when attempting to form the mask:
1 is not always wide enough

What problems happen when number is a wider type than 1?
x may be too great for the shift 1 << x leading to undefined behavior (UB). Even if x is not too great, ~ may not flip enough most-significant-bits.

// assume 32 bit int/unsigned
unsigned long long number = foo();

unsigned x = 40; 
number |= (1 << x);  // UB
number ^= (1 << x);  // UB
number &= ~(1 << x); // UB

x = 10;
number &= ~(1 << x); // Wrong mask, not wide enough

To insure 1 is wide enough:

Code could use 1ull or pedantically (uintmax_t)1 and let the compiler optimize.

number |= (1ull << x);
number |= ((uintmax_t)1 << x);

Or cast - which makes for coding/review/maintenance issues keeping the cast correct and up-to-date.

number |= (type_of_number)1 << x;

Or gently promote the 1 by forcing a math operation that is as least as wide as the type of number.

number |= (number*0 + 1) << x;

As with most bit manipulations, best to work with unsigned types rather than signed ones

@chqrlie 2017-09-27 22:27:57

Interesting look on an old question! Neither number |= (type_of_number)1 << x; nor number |= (number*0 + 1) << x; appropriate to set the sign bit of a signed type... As a matter of fact, neither is number |= (1ull << x);. Is there a portable way to do it by position?

@chux - Reinstate Monica 2017-09-27 22:33:49

@chqrlie IMO, the best way to avoid setting the sign bit and risking UB or IDB with shifts is to use unsigned types. Highly portable shift signed code is too convoluted to be acceptable.

@kapilddit 2012-06-05 14:18:25

For the beginner I would like to explain a bit more with an example:


value is 0x55;
bitnum : 3rd.

The & operator is used check the bit:

0101 0101
0000 1000
0000 0000 (mean 0: False). It will work fine if the third bit is 1 (then the answer will be True)

Toggle or Flip:

0101 0101
0000 1000
0101 1101 (Flip the third bit without affecting other bits)

| operator: set the bit

0101 0101
0000 1000
0101 1101 (set the third bit without affecting other bits)

@Gokul Naathan 2012-02-28 19:27:26

This program is to change any data bit from 0 to 1 or 1 to 0:

    unsigned int data = 0x000000F0;
    int bitpos = 4;
    int bitvalue = 1;
    unsigned int bit = data;
    bit = (bit>>bitpos)&0x00000001;
    int invbitvalue = 0x00000001&(~bitvalue);

    if (bitvalue == 0)
        if (bit == 0)
            printf("%x\n", data);
             data = (data^(invbitvalue<<bitpos));
             printf("%x\n", data);
        if (bit == 1)
            printf("elseif %x\n", data);
            data = (data|(bitvalue<<bitpos));
            printf("else %x\n", data);

@thangavel 2009-04-11 23:05:16

Use this:

int ToggleNthBit ( unsigned char n, int num )
    if(num & (1 << n))
        num &= ~(1 << n);
        num |= (1 << n);

    return num;

@asdf 2011-07-02 19:33:00

Well, it uses inefficient branching.

@M.M 2015-02-06 23:53:56

@asdf The compiler's job is to output the most efficient binary, the programmer's job is to write clear code

@Ben Voigt 2015-02-22 02:18:34

This is a good demonstration of testing, setting, and clearing a particular bit. However it's a very bad approach for toggling a bit.

@sam msft 2015-02-06 23:11:18

Here are some macros I use:

SET_FLAG(Status, Flag)            ((Status) |= (Flag))
CLEAR_FLAG(Status, Flag)          ((Status) &= ~(Flag))
INVALID_FLAGS(ulFlags, ulAllowed) ((ulFlags) & ~(ulAllowed))
TEST_FLAGS(t,ulMask, ulBit)       (((t)&(ulMask)) == (ulBit))
IS_FLAG_SET(t,ulMask)             TEST_FLAGS(t,ulMask,ulMask)
IS_FLAG_CLEAR(t,ulMask)           TEST_FLAGS(t,ulMask,0)

@kendotwill 2014-05-08 04:33:41

Expanding on the bitset answer:

#include <iostream>
#include <bitset>
#include <string>

using namespace std;
int main() {
  bitset<8> byte(std::string("10010011");

  // Set Bit
  byte.set(3); // 10010111

  // Clear Bit
  byte.reset(2); // 10010101

  // Toggle Bit
  byte.flip(7); // 00010101

  cout << byte << endl;

  return 0;

@dmckee --- ex-moderator kitten 2008-09-08 21:07:03

It is sometimes worth using an enum to name the bits:

enum ThingFlags = {
  ThingMask  = 0x0000,
  ThingFlag0 = 1 << 0,
  ThingFlag1 = 1 << 1,
  ThingError = 1 << 8,

Then use the names later on. I.e. write

thingstate |= ThingFlag1;
thingstate &= ~ThingFlag0;
if (thing & ThingError) {...}

to set, clear and test. This way you hide the magic numbers from the rest of your code.

Other than that I endorse Jeremy's solution.

@endolith 2011-12-20 15:09:13

Alternately you could make a clearbits() function instead of &= ~. Why are you using an enum for this? I thought those were for creating a bunch of unique variables with hidden arbitrary value, but you're assigning a definite value to each one. So what's the benefit vs just defining them as variables?

@dmckee --- ex-moderator kitten 2011-12-22 01:15:44

@endolith: The use of enums for sets of related constants goes back a long way in c programing. I suspect that with modern compilers the only advantage over const short or whatever is that they are explicitly grouped together. And when you want them for something other than bitmasks you get the automatic numbering. In c++ of course, they also form distinct types which gives you a little extras static error checking.

@Luis Colorado 2014-09-30 10:55:14

You'll get into undefined enum constants if you don't define a constant for each of the possible values of the bits. What's the enum ThingFlags value for ThingError|ThingFlag1, for example?

@Lundin 2015-12-14 09:25:32

If you use this method please keep in mind that enum constants are always of signed type int. This can cause all manner of subtle bugs because of implicit integer promotion or bitwise operations on signed types. thingstate = ThingFlag1 >> 1 will for example invoke implementation-defined behavior. thingstate = (ThingFlag1 >> x) << y can invoke undefined behavior. And so on. To be safe, always cast to an unsigned type.

@Aiken Drum 2016-03-15 15:01:59

@Lundin: As of C++11, you can set the underlying type of an enumeration, e.g.: enum My16Bits: unsigned short { ... };

@R.. GitHub STOP HELPING ICE 2010-07-13 06:53:05

Here's my favorite bit arithmetic macro, which works for any type of unsigned integer array from unsigned char up to size_t (which is the biggest type that should be efficient to work with):

#define BITOP(a,b,op) \
 ((a)[(size_t)(b)/(8*sizeof *(a))] op ((size_t)1<<((size_t)(b)%(8*sizeof *(a)))))

To set a bit:

BITOP(array, bit, |=);

To clear a bit:

BITOP(array, bit, &=~);

To toggle a bit:

BITOP(array, bit, ^=);

To test a bit:

if (BITOP(array, bit, &)) ...


@foraidt 2010-07-13 08:27:40

It's good to read but one should be aware of possible side effects. Using BITOP(array, bit++, |=); in a loop will most likely not do what the caller wants.

@R.. GitHub STOP HELPING ICE 2010-07-13 09:19:46

Indeed. =) One variant you might prefer is to separate it into 2 macros, 1 for addressing the array element and the other for shifting the bit into place, ala BITCELL(a,b) |= BITMASK(a,b); (both take a as an argument to determine the size, but the latter would never evaluate a since it appears only in sizeof).

@PC Luddite 2015-10-23 17:08:19

@R.. This answer is really old, but I'd probably prefer a function to a macro in this case.

@chux - Reinstate Monica 2017-09-27 17:58:06

Minor: the 3rd (size_t) cast seem to be there only to insure some unsigned math with %. Could (unsigned) there.

@chux - Reinstate Monica 2017-09-27 18:00:43

The (size_t)(b)/(8*sizeof *(a)) unnecessarily could narrow b before the division. Only an issue with very large bit arrays. Still an interesting macro.

@Ferruccio 2008-09-11 00:56:12

The other option is to use bit fields:

struct bits {
    unsigned int a:1;
    unsigned int b:1;
    unsigned int c:1;

struct bits mybits;

defines a 3-bit field (actually, it's three 1-bit felds). Bit operations now become a bit (haha) simpler:

To set or clear a bit:

mybits.b = 1;
mybits.c = 0;

To toggle a bit:

mybits.a = !mybits.a;
mybits.b = ~mybits.b;
mybits.c ^= 1;  /* all work */

Checking a bit:

if (mybits.c)  //if mybits.c is non zero the next line below will execute

This only works with fixed-size bit fields. Otherwise you have to resort to the bit-twiddling techniques described in previous posts.

@R.. GitHub STOP HELPING ICE 2010-06-28 06:17:34

I've always found using bitfields is a bad idea. You have no control over the order in which bits are allocated (from the top or the bottom), which makes it impossible to serialize the value in a stable/portable way except bit-at-a-time. It's also impossible to mix DIY bit arithmetic with bitfields, for example making a mask that tests for several bits at once. You can of course use && and hope the compiler will optimize it correctly...

@Lundin 2011-08-18 19:19:51

Bit fields are bad in so many ways, I could almost write a book about it. In fact I almost had to do that for a bit field program that needed MISRA-C compliance. MISRA-C enforces all implementation-defined behavior to be documented, so I ended up writing quite an essay about everything that can go wrong in bit fields. Bit order, endianess, padding bits, padding bytes, various other alignment issues, implicit and explicit type conversions to and from a bit field, UB if int isn't used and so on. Instead, use bitwise-operators for less bugs and portable code. Bit fields are completely redundant.

@Ferruccio 2011-08-18 19:35:12

Like most language features, bit fields can be used correctly or they can be abused. If you need to pack several small values into a single int, bit fields can be very useful. On the other hand, if you start making assumptions about how the bit fields map to the actual containing int, you're just asking for trouble.

@endolith 2012-03-08 19:47:54

So the bit order is arbitrary and you can't use this to twiddle individual bits in a microcontroller?

@Ferruccio 2012-03-08 21:02:38

@endolith: That would not be a good idea. You could make it work, but it wouldn't necessarily be portable to a different processor, or to a different compiler or even to the next release of the same compiler.

@iGbanam 2012-11-28 22:39:09

This is awesome. My question though is: after checking the sizeof(mybits), I get 12 (i.e. size of three ints). Is this the space allocated in memory or some bug in the sizeof function?

@Ferruccio 2012-11-29 00:36:30

@Yasky - what compiler are you using? I get 4 with both VC++11 and Clang 3.1.

@iGbanam 2012-11-29 01:02:27

@Ferruccio I am using gcc version 4.4.5

@Shade 2014-05-17 04:59:56

@R. It is possible to use both, the struct can be put inside a (usually anonymous) union with an integer etc. It works. (I realize this is an old thread btw)

@Lundin 2015-12-14 09:30:22

@Shade There are no guarantees that the bit field bits map in a sane, predictable manner to the other data types in the same union. All such code will at best be completely non-portable.

@Kelly S. French 2016-12-08 16:11:42

@Yasky and Ferruccio getting different answers to a sizeof() for this approach should illustrate the problems with compatibility not just across compilers but across hardware. We sometimes fool ourselves that we've solved these issues with languages or defined runtimes but it really comes down to 'will it work on my machine?'. You embedded guys have my respect (and sympathies).

@user13709754 2020-06-28 00:57:33

you might want __attribute__((packed))

@Jason 2012-04-30 06:48:43

Use one of the operators as defined here.

To set a bit, used int x = x | 0x?; where ? is the bit position in binary form.

@Ben Voigt 2015-02-22 02:20:34

0x is the prefix for a literal in hexadecimal, not binary.

@John U 2012-06-14 15:23:17

As this is tagged "embedded" I'll assume you're using a microcontroller. All of the above suggestions are valid & work (read-modify-write, unions, structs, etc.).

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.

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 much faster reaction and smaller assembled code.

@John U 2012-06-19 17:33:18

Micro was Coldfire MCF52259, using C in Codewarrior. Looking at the disassembler / asm is a useful exercise as it shows all the steps the CPU has to go through to do even the most basic operation. <br>We also spotted other CPU-hogging instructions in time-critical loops - constraining a variable by doing var %= max_val costs a pile of CPU cycles every time round, while doing if(var > max_val)var-=max_val uses only a couple of instructions. <br>A good guide to a few more tricks is here:…

@Ben Voigt 2015-02-22 02:16:20

Even more importantly, the helper memory-mapped I/O registers provide a mechanism for atomic updates. Read/modify/write can go very badly if the sequence is interrupted.

@Lundin 2015-12-14 09:42:09

Keep in mind that all port registers will be defined as volatile and therefore the compiler is unable to perform any optimizations on code involving such registers. Therefore, it is good practice to disassemble such code and see how it turned out on assembler level.

@bill 2009-06-13 21:27:39

More general, for arbitrary sized bitmaps:

#define BITS 8
#define BIT_SET(  p, n) (p[(n)/BITS] |=  (0x80>>((n)%BITS)))
#define BIT_CLEAR(p, n) (p[(n)/BITS] &= ~(0x80>>((n)%BITS)))
#define BIT_ISSET(p, n) (p[(n)/BITS] &   (0x80>>((n)%BITS)))

@M.M 2015-02-06 23:52:34

CHAR_BIT is already defined by limits.h, you don't need to put in your own BITS (and in fact you make your code worse by doing so)

@John Zwinck 2009-01-03 23:44:14

Check a bit at an arbitrary location in a variable of arbitrary type:

#define bit_test(x, y)  ( ( ((const char*)&(x))[(y)>>3] & 0x80 >> ((y)&0x07)) >> (7-((y)&0x07) ) )

Sample usage:

int main(void)
    unsigned char arr[8] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };

    for (int ix = 0; ix < 64; ++ix)
        printf("bit %d is %d\n", ix, bit_test(arr, ix));

    return 0;

Notes: This 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.

@Roddy 2008-11-06 11:30:16

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.

struct HwRegister {
    unsigned int errorFlag:1;  // one-bit flag field
    unsigned int Mode:3;       // three-bit mode field
    unsigned int StatusCode:4;  // four-bit status code

struct HwRegister CR3342_AReg;

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.

You can then read, write, test the individual values as before.

@Lundin 2011-08-18 19:50:26

Pretty much everything about bit-fields is implementation-defined. Even if you manage to find out all details regarding how your particular compiler implements them, using them in your code will most certainly make it non-portable.

@Roddy 2011-08-19 20:13:25

@Lundin - True, but embedded system bit-fiddling (particularly in hardware registers, which is what my answer relates to) is never going to be usefully portable anyway.

@Lundin 2011-08-20 09:35:20

Not between entirely different CPUs perhaps. But you most likely want it to be portable between compilers and between different projects. And there is a lot of embedded "bit-fiddling" that isn't related to the hardware at all, such as data protocol encoding/decoding.

@user1899861 2013-02-15 22:26:53

...and if you get in the habit of using bit fields doing embedded programming, you'll find your X86 code runs faster, and leaner too. Not in simple benchmarks where you have the whole machine to crush the benchmark, but in real-world multi-tasking environments where programs compete for resources. Advantage CISC - whose original design goal was to make up for CPUs faster than buses and slow memory.

Related Questions

Sponsored Content

1 Answered Questions

[SOLVED] The Definitive C++ Book Guide and List

  • 2008-12-23 05:23:56
  • grepsedawk
  • 2404596 View
  • 4242 Score
  • 1 Answer
  • Tags:   c++ c++-faq

26 Answered Questions

10 Answered Questions

10 Answered Questions

54 Answered Questions

[SOLVED] How to count the number of set bits in a 32-bit integer?

10 Answered Questions

[SOLVED] Improve INSERT-per-second performance of SQLite

9 Answered Questions

18 Answered Questions

[SOLVED] What is the difference between const int*, const int * const, and int const *?

4 Answered Questions

[SOLVED] How do you set, clear and toggle a single bit in JavaScript?

5 Answered Questions

[SOLVED] Extracting bits with a single multiplication

Sponsored Content