How to Use Left Shift Operator in Embedded C: Syntax and Examples
In Embedded C, the
<< operator shifts bits of a number to the left by a specified number of positions, effectively multiplying the number by 2 for each shift. Use it as value << n, where value is the number and n is the number of bit positions to shift.Syntax
The left shift operator syntax in Embedded C is simple:
value << n: Shifts bits ofvalueto the left bynpositions.- Each shift to the left multiplies the number by 2.
- Bits shifted out on the left are discarded, and zeros fill in from the right.
c
result = value << n;
Example
This example shows how to use the left shift operator to multiply a number by powers of two in Embedded C.
c
#include <stdio.h> int main() { unsigned int value = 5; // binary: 0000 0101 unsigned int shifted = value << 3; // shift left by 3 bits printf("Original value: %u\n", value); printf("Value after left shift by 3: %u\n", shifted); return 0; }
Output
Original value: 5
Value after left shift by 3: 40
Common Pitfalls
Common mistakes when using the left shift operator include:
- Shifting by a number greater or equal to the bit width of the data type causes undefined behavior.
- Using signed integers can lead to unexpected results due to sign bit shifts.
- Not considering overflow when bits shifted out are lost.
Always use unsigned types for predictable behavior and ensure the shift count is less than the bit width (usually 8, 16, 32, or 64).
c
#include <stdio.h> int main() { signed int value = -1; unsigned int safe_value = 1; // Wrong: shifting signed negative number int wrong_shift = value << 1; // Right: use unsigned to avoid sign issues unsigned int right_shift = safe_value << 1; printf("Wrong shift result: %d\n", wrong_shift); printf("Right shift result: %u\n", right_shift); return 0; }
Output
Wrong shift result: -2
Right shift result: 2
Quick Reference
Tips for using the left shift operator in Embedded C:
- Use
<<to multiply by powers of two. - Always use unsigned integers to avoid sign-related issues.
- Do not shift by more than or equal to the bit size of the variable.
- Remember bits shifted out are lost, so watch for overflow.
Key Takeaways
The left shift operator
<< moves bits left, multiplying the number by 2 for each shift.Always use unsigned integers to avoid unexpected results with sign bits.
Never shift by a number equal to or larger than the variable's bit width to prevent undefined behavior.
Bits shifted out on the left are lost, so be careful of overflow.
Use left shift for efficient multiplication by powers of two in embedded systems.