Sep
25

How to set, clear ,toggle and check a single bit in C?

As being an embedded software engineer i would really suggest you this tricks. ..!  In many  application you need to deal with this bit wise operation. Sometimes you know this all stuff very well but still some time it takes  time to construct this logic or some time you got some mistakes in it. so i suggest you to paste this on your desk until you paste this in your mind..!

To set a bit

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

 number |= 1 << x; 

That will set bit x.

To clear a bit

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

 number &= ~(1 << x); 

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

To toggle a bit

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

 number ^= 1 << x; 

That will toggle bit x.

To check state of a bit

To check a bit, AND it with the bit you want to check:

 bit = number & (1 << x); 

That will put the value of bit x into the variable bit.

 

NOTE : here x is the position of bit starting from 0 to LSB.

 

JIGAR PATEL

hey I am an Artist who love to write code…! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here JigAr Patel

More PostsWebsiteTwitterFacebook

You may like to read this also....

2 Comments to “How to set, clear ,toggle and check a single bit in C?”

  • diablo 3 October 22, 2011 at 6:49 am

    Hi there, just required you to know I he added your internet site to my Google bookmarks due to your layout. But seriously, I feel your net internet site has 1 in the freshest theme I??ve came across. It extremely helps make reading through your website significantly easier.

  • Rahul March 3, 2013 at 8:24 am

    Seriously just one comment on such a good post ? There’s one question though. Why XOR ? Why not use the NOT operator ?

Post comment

*

CommentLuv badge
Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

latest comments

Find us on Facebook

Top Authors

35 posts
saurabh
22 posts
10 posts

Find us on stackoverflow

Polls

Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link