Chapter 34 of 37

Bitwise Operations

Computers store integer values internally as bits, which are 0s and 1s.

C provides special operators that allow us to work directly with these individual bits. These are called bitwise operators.

What are Bitwise Operations?

Bitwise operations perform operations on the individual bits of an integer value.

For example:

5  →  0101
3  →  0011

A bitwise AND operation works on these bits individually.


Bitwise Operators in C

Operator

Name

Description

&

AND

1 if both bits are 1

`

`

OR

^

XOR

1 if the bits are different

~

NOT

Flips each bit

<<

Left Shift

Shifts bits to the left

>>

Right Shift

Shifts bits to the right

1. Bitwise AND &

int result = 5 & 3;

Binary:

  0101
& 0011
------
  0001

So the result is:

1

2. Bitwise OR |

int result = 5 | 3;

Binary:

  0101
| 0011
------
  0111

Result:

7

3. Bitwise XOR ^

XOR produces 1 when the two bits are different.

int result = 5 ^ 3;

Binary:

  0101
^ 0011
------
  0110

Result:

6

4. Bitwise NOT ~

~ flips every bit:

0 → 1
1 → 0

For example:

int result = ~5;

The exact decimal result depends on the integer representation and type, so for now, focus on the idea that ~ flips the bits.


5. Left Shift <<

The left-shift operator moves bits to the left.

int result = 5 << 1;

Binary:

0101  →  1010

So the result is:

10

6. Right Shift >>

The right-shift operator moves bits to the right.

int result = 8 >> 1;

Binary:

1000  →  0100

Result:

4

The exact behavior of right-shifting negative signed integers is implementation-defined, so bitwise examples are best understood first with non-negative integers.


Where are Bitwise Operations Used?

Bitwise operations are especially useful in:

  • Embedded systems

  • Device drivers

  • Operating systems

  • Network programming

  • Cryptography

  • Flags and permissions

  • Memory and hardware-level programming

For example, we can use individual bits as on/off flags.

00000001 → Flag 1
00000010 → Flag 2
00000100 → Flag 3

This allows multiple settings to be stored efficiently in a single integer.

In Simple Words

Bitwise operations allow us to manipulate the individual bits of integer values.

Remember the six main operators:

&   → AND
|   → OR
^   → XOR
~   → NOT
<<  → Left Shift
>>  → Right Shift

You don't need to master binary calculations immediately. Once you understand how bits work, these operators become much easier to use.