# Bitwise OR (|) operator

Bitwise OR (|) operator will take two equal length binary sequence and perform bitwise OR operation on each pair of bit sequence.

Bitwise OR will return 1, if any of the bit in the pair is 1.

If both bits are 0, then the outcome will be 0.

Truth table of OR(|),

Ai

Bi

A i | Bi

0

0

0

0

1

1

1

0

1

1

1

1

#### Example

Let’s take two integers say A = 10 and B = 12,

Then A | B will be,

## What is the use of bitwise OR (|) operator ?

Let’s take a scenario where we are going to design a robot car which uses a sensor to sense the environment and update it's direction accordingly.

Directions = {left, right, forward, backward}.

We are going to use 4 bits, each one for each direction.

#### Pictorial Explanation

Whenever the sensor wants to update any status, it will use the above four bits and set the status. Like, if the sensor sets first bit as 1 which indicates that the car should turn to the right direction.

Here, we need to enable bits according to sensor input.

## How will you enable specific bit programmatically?

Using bitwise OR operator, we can enable a specific bit.

#### Example

Let’s assume the sensor senses something and it wants to indicate the car to take the right direction.So, we need enable first bit as 1. Because first bit is reserved for right direction.

To update the bit status, we need to create a binary OR MASK.

OR MASK should have only one 1 in some position where we need to enable the bit status.

And it should have the remaining bits as 0.

In our case, we need to enable first bit,

So OR MASK = 0001 (right 1, remaining directions are 0)

Now take Sensor status OR MASK,

Sensor status                  = 0000

Sensor status | MASK      = 0001

Right direction bit has set as 1.

Similarly if we want to enable left direction bit,

MASK will be 0010 (left 1, remaining 0)

Now take sensor status | MASK,

Sensor status                  = 0000