- How the
>>operator shifts bits to the right - Why
n >> kis equivalent ton ÷ 2k(integer division) - The difference between arithmetic shift (sign-preserving) and logical shift (zero-filling)
- How signed vs. unsigned operands behave differently
- How right shift extracts bits — the building block for binary printing
The right shift operator
The bitwise right shift operator >> takes two operands: the value to shift and the number of positions to shift. n >> k moves every bit of n to the right by k positions. Bits that are shifted off the right edge are discarded; the vacated high-order bits are filled with either 0 (logical shift) or copies of the sign bit (arithmetic shift).
In other words: each right shift by 1 halves the value (for non-negative numbers). 20 >> 1 = 10, 20 >> 2 = 5, 20 >> 3 = 2 (note: 20/8 = 2.5, truncated to 2). The last example shows that right shift performs integer division — the fractional part is discarded.
Common uses of >>:
- Fast division —
n >> 3is faster thann / 8on some architectures (modern compilers often make this optimization automatically). - Extracting bits —
(n >> k) & 1extracts bitk— the standard way to print binary. - Reading packed fields — extract a byte or nibble from a packed word.
- Dropping low bits —
n >> 4discards the low 4 bits, keeping only the high bits.
n >> k shifts bits right by k positions, equivalent to integer division by 2k. Bits that fall off the right are lost; zeros (or the sign bit) fill in on the left, depending on signed/unsigned.
The divide-by-2n rule
For non-negative n and a shift count k such that 0 ≤ k < bit-width, the identity is:
n >> k == n ÷ 2k (integer division, truncated)
Examples:
20 >> 0 = 20 ÷ 20 = 20 ÷ 1 = 2020 >> 1 = 20 ÷ 21 = 20 ÷ 2 = 1020 >> 2 = 20 ÷ 22 = 20 ÷ 4 = 520 >> 3 = 20 ÷ 23 = 20 ÷ 8 = 2(truncated from 2.5)1024 >> 10 = 1024 ÷ 1024 = 1
This identity is why right shift is often called "divide by power of 2." Note the truncation: 20 >> 3 = 2, not 2.5 — right shift on integers is integer division, same as 20 / 8 = 2.
Shift example with binary representation — 20 >> 2:
Each shift moves the bits one position to the right and fills the leftmost bit with 0 (for non-negative numbers). The value halves with each shift, with truncation on odd values.
Arithmetic vs. logical shift
For non-negative numbers (where the sign bit is 0), right shift simply fills the high bits with 0. For negative numbers (sign bit is 1), there are two possible behaviors:
- Arithmetic shift — fills with copies of the sign bit (1 for negative). Preserves the sign and the "divide by 2" semantics.
−20 >> 2 = −5. - Logical shift — fills with 0. Turns a negative number into a very large positive one.
−20 >> 2 = 1,073,741,819(on 32-bit int).
The C standard leaves the choice implementation-defined for signed integers (though virtually all modern compilers implement arithmetic shift, consistent with two's complement). For unsigned int, the standard mandates logical shift — no ambiguity.
Rule of thumb: if you might shift negative numbers, use unsigned int for predictable behavior. If you're only shifting non-negatives, int is fine and arithmetic = logical.
Complete C Program
Here is the program — right shift an integer by a specified count:
Program: Right shift an integer
#include <stdio.h>
int main(void) {
int n, k;
printf("Enter a number and a shift count: ");
scanf("%d %d", &n, &k);
if (k < 0 || k >= 32) {
printf("Error: shift count must be between 0 and 31\n");
return 1;
}
printf("%d >> %d = %d\n", n, k, n >> k);
return 0;
}
The variant with binary display makes the operation visible:
Variant: Show binary representation
#include <stdio.h>
void print_binary(int n) {
for (int i = 7; i >= 0; i--) {
printf("%d", (n >> i) & 1);
if (i % 4 == 0 && i != 0) printf(" ");
}
printf("\n");
}
int main(void) {
int n, k;
printf("Enter a number (0-255) and shift count (0-7): ");
scanf("%d %d", &n, &k);
if (k < 0 || k > 7) {
printf("Error: shift count must be between 0 and 7\n");
return 1;
}
printf("\nn = ");
print_binary(n);
printf("n >> %d = ", k);
print_binary(n >> k);
printf("\nDecimal result: %d\n", n >> k);
return 0;
}
The print_binary helper itself uses right shift — (n >> i) & 1 extracts bit i by shifting it down to position 0, then masking with 1. This is the standard "extract bit k" idiom, built directly on right shift.
Program Output
Sample run of the basic program:
Enter a number and a shift count: 20 2
20 >> 2 = 5
20 ÷ 22 = 20 ÷ 4 = 5 — correct.
More examples:
Enter a number and a shift count: 1024 10
1024 >> 10 = 1
1024 ÷ 210 = 1024 ÷ 1024 = 1 — right shift recovers the "power of 2" exponent when the value is exactly a power of 2.
Enter a number and a shift count: 7 1
7 >> 1 = 3
7 ÷ 2 = 3.5, truncated to 3. This is integer division — the fractional part is discarded, not rounded.
The variant with binary display:
Enter a number (0-255) and shift count (0-7): 20 2
n = 0001 0100
n >> 2 = 0000 0101
Decimal result: 5
The binary view makes it clear: the bits of 20 (0001 0100) moved two positions right, filling zeros on the left, producing 0000 0101 = 5.
Arithmetic shift on a negative number:
Enter a number and a shift count: -20 2
-20 >> 2 = -5
−20 ÷ 4 = −5 — arithmetic shift preserves the sign by filling the high bits with 1s (the sign bit). This matches the divide rule.
Step-by-Step Explanation
1. Declarations: int n, k; — n is the value to shift, k is the shift count. Both are integers.
2. Input validation: The check if (k < 0 || k >= 32) rejects shift counts outside the valid range. Shifting by a negative number or by a count ≥ the type's bit width is undefined behavior in C — the compiler may produce any result. Always validate before shifting.
3. The shift operation: n >> k moves each bit of n right by k positions. Each right shift divides the value by 2 (with truncation on odd values). 20 >> 2 = 5 because 20 ÷ 4 = 5.
4. Binary view: For 20 >> 2:
20in binary:0001 0100- Shift right by 2:
0000 0101(each bit moves 2 positions right; the two leftmost bits become 0) 0000 0101= 5 in decimal
5. Arithmetic vs. logical shift: For int (signed), the C standard leaves the fill behavior implementation-defined. On all modern compilers (two's complement hardware), >> on a signed negative value performs an arithmetic shift — fills with copies of the sign bit, preserving the sign. For unsigned int, the standard mandates logical shift — always fills with 0. If you need predictable behavior, use unsigned int.
6. Unsigned vs signed: For non-negative signed values, both shifts are identical (fill with 0). The distinction only matters for negative values. For example:
int n = −8; n >> 1=−4(arithmetic, sign-preserving).unsigned int u = 0xFFFFFFF8; u >> 1=0x7FFFFFFC(logical, zero-filling, gives a large positive number).
7. Overflow / underflow: Right shift doesn't have "overflow" in the usual sense — the bits shifted off the low end are just discarded, and the value decreases. However, shifting a very small value repeatedly eventually gives 0. 5 >> 1 = 2, 2 >> 1 = 1, 1 >> 1 = 0, 0 >> 1 = 0 — once all bits are shifted out, further shifts have no effect.
8. Extracting bits: The combination (n >> k) & 1 is the standard idiom for "get bit k of n." Shift bit k down to position 0, then mask off all other bits with & 1. This is how print_binary works — iterating k from high to low, printing one bit per step.
n >> k shifts bits right, dividing by 2k (integer division). For signed values, use int only if you're sure the value is non-negative; otherwise use unsigned int for predictable behavior. Always validate the shift count. Use (n >> k) & 1 to extract bit k.
Frequently Asked Questions
1. Why is n >> k not always the same as n / 2k?
For non-negative n, n >> k and n / 2k agree. For negative n, the behavior depends on the compiler's choice of arithmetic vs. logical shift. On two's-complement compilers (all modern ones), >> on a signed negative value performs arithmetic shift — −20 >> 2 = −5, same as −20 / 4 = −5. But if you cast to unsigned first, you'd get a completely different (large positive) result. So the "divide rule" is really: n >> k for signed n behaves like floor(n / 2k) on two's-complement machines.
2. What's the difference between arithmetic and logical shift?
Arithmetic shift fills the vacated high bits with copies of the sign bit (0 for positive, 1 for negative). This preserves the sign and the "divide by 2" semantics. Logical shift fills with 0, always. For positive numbers, both behaviors are identical (sign bit is 0). For negative numbers, arithmetic shift preserves the sign, while logical shift turns the value into a large positive number. C mandates logical shift for unsigned types; for signed types, it's implementation-defined (though modern compilers choose arithmetic).
3. What happens if I shift by a count ≥ the bit width?
It's undefined behavior in C — anything can happen. For int (32 bits), shifting by 32 or more is undefined. For long long (64 bits), shifting by 64 or more is undefined. Always validate 0 ≤ k < bit-width before shifting. On most x86 CPUs, the shift count is masked to 5 bits (for 32-bit shifts), so n >> 32 actually becomes n >> 0 = n — a common source of bugs that appear only on certain architectures.
4. How do I extract a specific bit?
Use (n >> k) & 1. This shifts bit k down to position 0, then masks off all other bits with & 1. For example, to check if bit 3 is set: if ((n >> 3) & 1). Equivalently, if (n & (1 << 3)) — the two forms are equivalent, and both are idiomatic. The shift-then-mask form is common when iterating over all bits (like in print_binary); the shift-mask-OR form is common when setting/clearing bits.
5. Is n / 2 faster than n >> 1?
In modern code, the compiler generates the same machine instruction for both (when n is non-negative). The division is clearer, and the compiler applies the strength reduction optimization to convert n / 2 into a shift. Use n / 2 for readability; use n >> 1 when the intent is explicitly bit-level manipulation. One subtlety: for negative n, n / 2 and n >> 1 can differ (C's / truncates toward zero, while arithmetic >> rounds toward −∞). So if n might be negative, prefer / 2 for clarity, or be explicit about which rounding you want.
💡 Tip: once this works, try these classic right shift applications: (a) extract bits with (n >> k) & 1, (b) split a packed word into bytes ((n >> 8) & 0xFF for the second byte), (c) fast divide by powers of 2 (n >> k), (d) print an integer in binary by iterating shifts, (e) compute parity by XORing shifted values (e.g., n ^= n >> 16; n ^= n >> 8; ...). Each is a small extension of the same operator.