Bitwise operators are used to perform operations at the bit level.

### Python supports the following Bitwise operators:

1) Bitwise AND(&)

2) Bitwise OR(|)

3) Bitwise XOR(^)

4) Bitwise NOT(~)

Bitwise operators expect their operands to be integers and treat them as a sequence of bits.

## Bitwise AND(&) operator

Bitwise AND operator is represented by a single ampersand(&) and is surrounded on both sides by integer expressions.

Actually, when we use the Bitwise AND operator, the bit in the first operand is ANDed with the corresponding bit in the second operand. The Bitwise-AND operator compares each bit of its first operand with the corresponding bit of its second operand.

The result of the ANDing operation is 1 if both the bits have a value of 1; otherwise, it is 0.

For example, 10101010&01010101=00000000

#### Example on Bitwise AND(&) operator:

a=30 b=20 c=a&b print(c)

##### Output:

20

## Bitwise OR(|) operator

Bitwise OR is represented by a symbol(|) and is surrounded on both sides by integer operands.

Actually, when we use the Bitwise OR operator, the bit in the first operand is ORed with the corresponding bit in the second operand. The Bitwise-OR operator compares each bit of its first operand with the corresponding bit of its second operand.

The result of OR operation is 1 if at least one of the bits has a value of 1; otherwise, it is 0.

For example, 10101010|01010101=11111111

#### Example on Bitwise OR(|) operator:

a=30 b=20 c=a|b print(c)

##### Output:

30

## Bitwise XOR(^) operator

Bitwise XOR is represented by a symbol(^) and is surrounded on both sides by integer operands.

Actually, when we use the Bitwise XOR operator, the bit in the first operand is XORed with the corresponding bit in the second operand. The Bitwise-XOR operator compares each bit of its first operand with the corresponding bit of its second operand.

The result of the XOR operation is 1 if only one of the bits is 1; otherwise, 0.

For example, 10101010^01010101=11111111

#### Example on Bitwise XOR(^) operator:

a=30 b=20 c=a^b print(c)

##### Output:

10

## Bitwise NOT(~) operator

The Bitwise NOT operator(~) is a unary operator, and it is also called one's complement operator. It converts all the bits represented by its operand. That is, 0s become 1s, and 1s becomes zero.

Consider the following example:

~10101010=01010101

#### Example on Bitwise NOT(~) operator:

a=30 b=~a print(b)

##### Output:

-31

Consider the following bitwise operations:

A B A&B A|B A^B 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0

## Leave a comment