InterviewBit Academy is now Scaler Academy!

- Courses
- Programming
- Bit Manipulation
- Bitwise Operators

TUTORIAL

1. What Is Binary Number System

2. Understanding Data Types Int

3. Bitwise Operators

4. Bitwise Operators ( Contd.. )

5. Tricks With Bits

6. Bitwise And Logical Operators :

As we discussed in the previous video, the numbers are stored in their binary representation in computers and every single digit 0 / 1 is called bit.

Most languages allow you to perform operations which are bitwise ( this statement will make much more sense when we look at the operator themselves ). It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations.

```
A & B
```

```
a b a & b
------------------------
0 0 0
0 1 0
1 0 0
1 1 1
```

In other words, `a & b = 0`

unless `a = 1 and b = 1`

.

A & B implies **a & b** for all corresponding bits of A and B.

So, lets say,

```
A = 21 ( 10101 ) and B = 6 ( 110 )
A & B =
1 0 1 0 1
& 0 0 1 1 0
------------------
0 0 1 0 0 = 4.
```

```
A | B
```

```
a b a | b
------------------------
0 0 0
0 1 1
1 0 1
1 1 1
```

In other words, `a | b = 1`

unless `a = 0 and b = 0`

`A | B`

implies ** a | b** for all corresponding bits of A and B.
So, lets say

```
A = 21 ( 10101 ) and B = 6 ( 110 )
A | B =
1 0 1 0 1
| 0 0 1 1 0
------------------
1 0 1 1 1 = 23.
```

```
A ^ B
```

```
a b a ^ b
------------------------
0 0 0
0 1 1
1 0 1
1 1 0
```

In other words, `a ^ b = 1`

when **a and b are different**.

A ^ B implies a ^ b for all corresponding bits of A and B. So, lets say

```
A = 21 ( 10101 ) and B = 6 ( 110 )
A ^ B =
1 0 1 0 1
^ 0 0 1 1 0
------------------
1 0 0 1 1 = 19.
```

```
~A
```

```
a | ~a
-------|-------
0 | 1
1 | 0
```

Its the **inverse of the bit**.

~A implies inverting every single bit in A. So, lets say

```
A = 21 ( 10101 ) and A is a char ( 1 byte )
~A =
0 0 0 1 0 1 0 1
--------------------------
1 1 1 0 1 0 1 0 = -22 ( Sign bit is 1 ).
```

Log In using

or