0
0
Embedded Cprogramming~5 mins

Left shift and right shift behavior in Embedded C

Choose your learning style9 modes available
Introduction

Left and right shifts move bits in a number to the left or right. This helps multiply or divide numbers quickly in low-level programming.

When you want to multiply a number by powers of two quickly.
When you need to divide a number by powers of two without using division.
When working with hardware registers to set or clear specific bits.
When optimizing code for speed in embedded systems.
When manipulating flags or masks in bitwise operations.
Syntax
Embedded C
result = value << n;  // Left shift value by n bits
result = value >> n;  // Right shift value by n bits

Left shift (<<) moves bits to the left, adding zeros on the right.

Right shift (>>) moves bits to the right. For unsigned values, zeros are added on the left. For signed values, behavior may depend on the compiler (logical vs arithmetic shift).

Examples
Left shift by 1 doubles the number (5 * 2 = 10).
Embedded C
unsigned int x = 5;  // binary 0000 0101
unsigned int y = x << 1;  // y = 10 (0000 1010)
Right shift by 2 divides the number by 4 (20 / 4 = 5).
Embedded C
unsigned int x = 20;  // binary 0001 0100
unsigned int y = x >> 2;  // y = 5 (0000 0101)
Right shift on signed negative numbers may keep the sign bit to preserve the sign.
Embedded C
int x = -8;  // binary depends on system
int y = x >> 1;  // may keep sign bit (arithmetic shift)
Sample Program

This program shows how left and right shifts work on unsigned and signed integers. It prints the original values and the results after shifting.

Embedded C
#include <stdio.h>

int main() {
    unsigned int a = 3;  // binary 0000 0011
    unsigned int left_shift = a << 2;  // shift left by 2 bits
    unsigned int right_shift = a >> 1; // shift right by 1 bit

    printf("Original a = %u\n", a);
    printf("a << 2 = %u\n", left_shift);
    printf("a >> 1 = %u\n", right_shift);

    int b = -16;  // signed integer
    int b_right_shift = b >> 2;  // right shift signed
    printf("Original b = %d\n", b);
    printf("b >> 2 = %d\n", b_right_shift);

    return 0;
}
OutputSuccess
Important Notes

Left shifting a number by n bits multiplies it by 2^n, but be careful of overflow.

Right shifting unsigned numbers fills with zeros on the left (logical shift).

Right shifting signed numbers may fill with the sign bit (arithmetic shift), preserving the sign.

Summary

Left shift (<<) moves bits left, multiplying by powers of two.

Right shift (>>) moves bits right, dividing by powers of two for unsigned numbers.

Signed right shift may keep the sign bit to preserve negative values.