Bit-wise shift
The bit shifts are sometimes considered bitwise operations, because they treat a value as a series of bits rather than as a numerical quantity. In these operations, the digits are moved, or shifted, to the left or right. Registers in a computer processor have a fixed width, so some bits will be "shifted out" of the register at one end, while the same number of bits are "shifted in" (or filled in) from the other end.
Bitwise shift operations, specifically left shift (<<
) and right shift (>>
), are fundamental to low-level programming and are used to manipulate the binary representation of numbers. A left shift operation (<<
) moves all the bits in a binary number to the left by a specified number of positions, filling the vacated bits with zeros. This effectively multiplies the number by 2 for each shift. For example, applying a left shift by 1 to the binary number 0010
(which is 2 in decimal) results in 0100
(which is 4 in decimal). This operation is commonly used in scenarios where fast multiplication by powers of 2 is required.
Conversely, the right shift operation (>>
) moves the bits of a binary number to the right, discarding the rightmost bits and either filling the leftmost bits with zeros (logical shift) or preserving the sign bit (arithmetic shift). This operation divides the number by 2 for each shift, ignoring remainders. For example, applying a right shift by 1 to 0100
(4 in decimal) results in 0010
(which is 2). Right shifts are particularly useful for efficient division by powers of 2 or when dealing with binary flags or masks in low-level bit manipulation.