Take the 2-minute tour ×
typedef unsigned int  StatusCode;

StatusCode quality = 0;

#define PARTIALBIT 0x05

quality |= PARTIALBIT ;// I am setting a partial bit here

// ....

At other part of code I have to check if paritial bit is set and I have to clear it. How do I acheive this in C ?


share|improve this question
I'll only give you a hint: Clearing a bit involves bitwise and and bitwise negation. –  Joachim Pileborg Aug 3 '12 at 10:15
By the way, you do know that in the example in your question you set two bits? Bits 0 and 2. You are not setting bit 5. –  Joachim Pileborg Aug 3 '12 at 10:17
add comment

3 Answers

up vote 4 down vote accepted

Try this:

if (quality & PARTIALBIT)
    // bit was set, do processing
    // ...
    // then clear the bit
    quality &= ~PARTIALBIT;

Also, if you have to set bit 5, then you're on the wrong way. If you want to set bit 5, use:

#define PARTIALBIT (1 << 5)


share|improve this answer
Actually you don't need to check if it's set. It's a superfluous operation. –  m0skit0 Aug 3 '12 at 10:16
I do read the comments, but I personally can't time-travel to the future. When I commented, there were no such comments in your code. You posted those comments 4 minutes later (probably due to my comment anyway...). Also, I upvoted your answer anyway, so try to not make such useless rude bold comments... –  m0skit0 Aug 3 '12 at 12:54
@m0skit0 first of all, thanks for the upvote. Second, the modifications were not inspired by your comment - I answered my first thought quickly, then I added some clarification. In no way did I mean to be rude. –  user529758 Aug 3 '12 at 13:03
Ok, no hard feelings, mate ;) –  m0skit0 Aug 3 '12 at 13:07
add comment

Alternative - use a bitfield union on the 'unsigned int StatusCode':

typedef union{
  unsigned intStatus;
  unsigned bitStatus:sizeof(unsigned);
} S_statusCode;
share|improve this answer
add comment

If you want to set a bit x, you write:

val |= 1<<x

If you want to clear a bit x, you do:

val &= ~(1<<x)

If you want to inverse a bit x, you write:

val ^= 1<<x
share|improve this answer
% is the modulus operator. I think you want exclusive or (^) –  JeremyP Aug 3 '12 at 10:40
Hups! they are close on the keyboard ! –  alinsoar Aug 3 '12 at 10:57
add comment

Your Answer


