top of page
Search

# Bitwise operations In Embedded C

In this blog I will explain use of bitwise operators for performing some operations which are often required for microcontrollers programming.

Bitwise operators: & (AND), | (OR) , ~ (NOT) , ^ (XOR) etc.

Writing operation: In microcontroller programming we often have to alter/change some bits of a register/memory location or an I/O port. This can be easily accomplished by using bitwise operators.

Examples:

Let's suppose we have to set (logic 1) port pin no.-1 of a microcontroller without changing any other pins.

lets assume the port is linked with some register " PORT0"

We are assuming that the port contain 16 pins.

PORT0 | = (1<<1);

So this operation is equivalent to : Content of PORT0 register | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

PORT0 | = (3<<1);

PORT0 = PORT0 | 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0

At this point we know how to set a bit of a register. Now, let's understand how to clear (logic 0) bits without affecting other bits of a register.

Clear bit no 1 and 2 of a register " R0" of a microcontroller.

If we write R0 = 0x0000 then this syntax will clear all the bits of R0. As we need to clear bit no 1 and 2 only so we have to modify our syntax.

R0 & = ~(3<<1);

This operation is equivalent to :

R0 = R0 & 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1

Clear bit no. 4 and 7

R0 & = ~((1<<4) |(1<<7));

Use of ^ (XOR) operator

The ^ operator is used to perform the exclusive or operation between two numbers.

Let's consider a case where we want to toggle the bits of a register R0.

This can easily be done by using the ^ operator.

R0 ^= R0

This is equivalent to R0 = R0 ^R0