Bitwise Operators & Masks Flashcards

1
Q

The &laquo_space;and&raquo_space; bit shift operators shift the binary value of the integer on the left of the number by the number on the right of the operator:

int x = 4;
x &laquo_space;2;

What is notable about the shift pattern in terms of the end value of the shift compared to the original value?

A

Left shifts double the value of the integer, while right shifts half the value of the integer.
Left: x * 2^n
Right: x / 2 ^n
Where n is the number of shifts.

Longer explanation:

In the example, x is 4. The binary of 4 is:
0100

A left shift by two moves all the bits 4 two places to the left.

0100 becomes 010000

010000 = 16

Notice that 16 is 4 doubled twice.
42 = 8, 82 = 16

In other words, the value of the integer is multiplied by 2^n where n is the number of shifts. Above there were 2 shifts left, and so it’s 4 * 2^2, which is 4*4 = 16.

The same applies for right shifts, but you divide instead of multiply, so right shifts have the effect of halving the number each time the bit shifts. In that case, the formula would be x / 2^n. Special note here: The result of the division drops decimals just like normal integer division.
So if we do: 5&raquo_space; 2, we get:

5 / 2^n =
5 / 2^2 =
5 / 4 = 1.25
and the .25 will be dropped to give a final value of 1, which in binary is just… 1. Or 0001 or whatever you want to use to convey that it’s binary 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly