//Bit Manipulation in C

Bit Manipulation in C

Writing programs for embedded systems often requires the manipulation of individual bits. Below is a list of the most common operations. In the examples we are performing them on an unsigned long variable called ctrl_reg.

Setting a bit

We can set a bit using the bitwise OR operator (|):

ctrl_reg |= 1UL << n;

The code above will set to 1 the bit in position n.

Clearing a bit

We can clear a bit using the bitwise AND operator (&) :

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

The code above will clear bit n.  We first invert the bits with the bitwise NOT operator (~) and then perform the AND operation.

Toggling a bit

We can use the XOR operator (^)  to toggle a bit.

ctrl_reg ^= 1UL << n;

The code above will toggle bit n.

Getting the value of a bit

We can get the value of a particular bit by shifting and then using bitwise AND operation:

bit_value = (ctrl_reg >> n) & 1UL;

That will put the value of bit n into the variable bit_value.

By |2018-08-17T22:57:56+00:00February 2nd, 2018|Categories: Explained Simply|Tags: , , |0 Comments

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

We use cookies on this site to improve our service, perform analytics and remember website preference. By using the site, you consent to these cookies. I consent to cookies