Introduction to Bit Shifting
A bit shift is a Bitwise operation where the order of a series of bits is moved, either to the left or right, to efficiently perform a mathematical operation.
Table of Contents
We learned the most common Bitwise operations so far. Now, we are about to learn shifting, which is a common operation we use when we divide/multiply a number by 2.
What is shifting?
A bit shift is a Bitwise operation where the order of a series of bits is moved, either to the left or right, to efficiently perform a mathematical operation.
A bit shift moves each digit in a number’s binary representation left or right. The bit-shifting operators do precisely what their name implies: they shift bits. Here is a brief introduction to the different shift operators.
Types
There are three main types of shifts:
- Left shift:
<<
is the left shift operator and meets both logical and arithmetic shifts’ needs. - Arithmetic/signed right shift:
>>
is the arithmetic (or signed) right shift operator. - Logical/unsigned right shift:
>>>
is the logical (or unsigned) right shift operator.
Note: <<<
is not an operator because it would be redundant.
These operators can be applied to integer values int
, long
, short
, byte
or char
.
In some languages, applying the shift operators to any datatype smaller than int
automatically resizes the operand to be an int
.
Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.