Resources | Subject Notes | Computer Science
This section explores bit manipulation techniques, focusing on binary shifts. Bitwise operators allow us to treat data as sequences of bits, enabling efficient operations like shifting bits left or right. Understanding these operations is crucial for low-level programming, data compression, and hardware interaction.
Binary shifts involve moving bits within a binary representation of a number. There are two main types of shifts: left shift and right shift.
The left shift operator (<<
) shifts the bits of a number to the left by a specified number of positions. Empty positions on the right are filled with zeros. Effectively, a left shift is equivalent to multiplying the number by $2^{\text{shift amount}}$.
Example:
Let's consider the number 5, which in binary is 00000101 (assuming 8-bit representation). Shifting it left by 2 positions gives:
00000101 shifted left by 2 becomes 00010100, which is 20 in decimal. This is equivalent to $5 \times 2^2 = 5 \times 4 = 20$
Syntax:
x << n
where x
is the number to be shifted and n
is the number of positions to shift.
Effect: Multiplies the number by $2^n$
The right shift operator (>>
) shifts the bits of a number to the right by a specified number of positions. The behavior of the right shift operator depends on whether the number is signed or unsigned.
Example (Unsigned):
Consider the number 20 (binary 00010100). Shifting it right by 2 positions gives:
00010100 shifted right by 2 becomes 00000101, which is 5 in decimal. This is equivalent to $20 \div 2^2 = 20 \div 4 = 5$
Example (Signed):
Consider the number -20 (binary 11101100 - assuming two's complement). Shifting it right by 2 positions gives:
11101100 shifted right by 2 becomes 11111101. The MSB (1) is copied to fill the empty positions. This is -5 in decimal. This is equivalent to $-20 \div 2^2 = -20 \div 4 = -5$
Syntax:
x >> n
where x
is the number to be shifted and n
is the number of positions to shift.
Effect: Divides the number by $2^n$ (for unsigned) or performs a division with sign (for signed).
Operator | Description | Effect | Example (5) |
---|---|---|---|
<< (Left Shift) |
Shifts bits to the left. | Multiplies by $2^n$ | 5 << 2 = 20 |
>> (Right Shift) |
Shifts bits to the right. | Divides by $2^n$ (unsigned) or division with sign (signed). | 5 >> 2 = 1 |
Bit shifts are used in various applications, including:
The number of bits used to represent a number (e.g., 8-bit, 16-bit, 32-bit) affects the behavior of bit shifts. Overflow can occur if the shifted value exceeds the maximum representable value for the given number of bits.