Bitwise operations are hard to understand for some beginning programmers. So this post is to explain them easily and unforgettably.

# What’s a **bit and bit string**?

A **bit** is the smallest unit of information that can be stored or manipulated on a computer. It consists of a single Boolean value (0 or 1).

A **bit string** is a sequence of **bits**. It can be used to represent sets or to manipulate **binary** data.

# Bitwise Operations

**Bitwise AND (&)**

The bitwise AND operator (`&`

) returns a `1`

in each bit position for which the corresponding bits of both operands (*input and mask*) are `1`

s.

Two principles:

a. `Y AND 1 = Y`

b. `Y AND 0 = 0`

Therefore, to** turn certain bits off,** `AND`

can be used with a `0`

.To leave a bit **unchanged**, `AND`

is used with a `1`

**Example**: Masking *on* the higher bits (bits 4,5,6) the lower bits (bits 0,1,2, 3) unchanged.

## Bitwise OR (|)

The bitwise OR operator (`|`

) returns a `1`

in each bit position for which the corresponding bits of either or both operands(*input and mask*) are `1`

s.

Principles:

a. `Y OR 1 = 1`

b. `Y OR 0 = Y`

Therefore, to **make certain bits on**, `OR`

can be used with a `1`

.To leave a bit **unchanged**, `OR`

is used with a `0.`

**Example**: Masking *on* the lower bits (bits 0,1, 2, 3) the higher bits (bits 4, 5, 6) unchanged.

## Bitwise exclusive OR (^)

The bitwise XOR operator (`^`

) returns a `1`

in each bit position for which the corresponding bits of either but not both operands (*input and mask*) are `1`

s

In another word, Bitwise exclusive OR sets 1 in each position where its operands have different bits, and 0 if they’re the same.

Two principles:

a.` Y `

*^ *0 = Y

b. *Y ^ a *= 0

## Left shift and Right shift

A **bit shift** moves each digit in a number’s binary representation left or right.

When shifting left, the most-significant bit is lost, and a 00 bit is inserted on the other end. When shifting right with a **logical right shift**, the least-significant bit is lost and a 00 is inserted on the other end.

# Bitmask Functions

## Getting a bit

To querying the status of a bit, shift the number `n`

to the right, then bitwise AND with`1`

`（number >> n) & 1`

## Setting a bit

To turn certain bits on, the bitwise `OR`

an operation can be used

`number |= 1 << n`

## Clearing a bit

Use the bitwise AND operator (`&`

) to clear a bit.

`number &= ~(1 << n)`

## Toggle a bit

The XOR operator (`^`

) can be used to toggle a bit.

`number ^= 1 << n`

# Bit manipulation Problems

After having an understanding of bit operations, now it’s time for practice.