How to Use Right Shift Operator in Embedded C
In Embedded C, the right shift operator
>> shifts the bits of a number to the right by a specified number of positions, effectively dividing the number by powers of two. Use it as variable >> number_of_bits to move bits right, filling left bits with zeros for unsigned types or sign bit for signed types.Syntax
The right shift operator syntax in Embedded C is:
result = value >> n;
Where:
valueis the integer variable or constant whose bits you want to shift.nis the number of bit positions to shift to the right.resultstores the shifted value.
For unsigned types, zeros fill the left bits. For signed types, the sign bit may be replicated (arithmetic shift).
c
result = value >> n;
Example
This example shows how to use the right shift operator to divide an unsigned integer by powers of two by shifting bits to the right.
c
#include <stdio.h> int main() { unsigned int value = 64; // binary: 01000000 unsigned int shifted1 = value >> 1; // shift right by 1 bit unsigned int shifted2 = value >> 3; // shift right by 3 bits printf("Original value: %u\n", value); printf("Value >> 1: %u\n", shifted1); printf("Value >> 3: %u\n", shifted2); return 0; }
Output
Original value: 64
Value >> 1: 32
Value >> 3: 8
Common Pitfalls
Common mistakes when using the right shift operator include:
- Shifting by a number greater or equal to the bit width of the type causes undefined behavior.
- Using right shift on signed integers may produce unexpected results due to sign bit replication.
- Assuming right shift always divides by powers of two without considering sign and type.
Always use unsigned types for predictable logical shifts.
c
#include <stdio.h> int main() { int signed_val = -16; // binary depends on system unsigned int unsigned_val = 16; int wrong_shift = signed_val >> 2; // may replicate sign bit unsigned int correct_shift = unsigned_val >> 2; // logical shift printf("Signed right shift: %d\n", wrong_shift); printf("Unsigned right shift: %u\n", correct_shift); return 0; }
Output
Signed right shift: -4
Unsigned right shift: 4
Quick Reference
| Operator | Description | Example | Result |
|---|---|---|---|
| >> | Right shift bits | 64 >> 1 | 32 (divides by 2) |
| >> | Right shift bits | 64 >> 3 | 8 (divides by 8) |
| >> | On signed int | -16 >> 2 | Depends on sign extension |
| >> | On unsigned int | 16 >> 2 | 4 (logical shift) |
Key Takeaways
Use the right shift operator >> to move bits right, effectively dividing by powers of two.
Prefer unsigned types for predictable logical right shifts without sign bit issues.
Never shift by a number equal to or larger than the bit width of the variable.
Right shifting signed integers may replicate the sign bit, causing arithmetic shifts.
Test shifts carefully on your target embedded platform for consistent behavior.