Operators Assignment 9 — Bitwise Left Shift on a Number Using the '<<' Operator
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Perform Bitwise Left Shift on a Number Using the '<<' Operator

📑 On this page:
  • The left shift operator
  • The multiply-by-2n rule
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How the << operator shifts bits to the left
  • Why n << k is equivalent to n × 2k
  • How bits shifted off the left edge are lost (overflow)
  • How bits are filled with zeros on the right
  • How to use left shift for fast multiplication by powers of 2

The left shift operator

The bitwise left 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 left by k positions, filling the vacated low-order bits with zeros. Bits that are shifted off the left edge are discarded (lost).

In other words: each left shift by 1 doubles the value. 5 << 1 = 10, 5 << 2 = 20, 5 << 3 = 40. This is because each bit in n moves to a position worth twice as much — bit k (worth 2k) becomes bit k+1 (worth 2k+1).

Common uses of <<:

  • Fast multiplication — n << 3 is faster than n * 8 on some architectures (modern compilers often make this optimization automatically).
  • Setting a bit — 1 << k produces a mask with only bit k set.
  • Building bit patterns — construct flags, colors, or packed fields.
  • Powers of 2 — 1 << n is the nth power of 2.
💡 In one line: n << k shifts bits left by k positions, equivalent to multiplying by 2k. Bits that fall off the left are lost; zeros fill in on the right.
Bitwise left shift in C — shifting bits of an integer to the left by a specified number of positions.

The multiply-by-2n rule

For non-negative n and a shift count k such that n × 2k doesn't overflow the type, the identity is:

n << k == n × 2k

Examples:

  • 5 << 0 = 5 × 20 = 5 × 1 = 5
  • 5 << 1 = 5 × 21 = 5 × 2 = 10
  • 5 << 2 = 5 × 22 = 5 × 4 = 20
  • 5 << 3 = 5 × 23 = 5 × 8 = 40
  • 1 << 10 = 1 × 210 = 1024

This identity is why left shift is often called "multiply by power of 2." It's exact for non-negative integers and doesn't overflow. For negative numbers, the behavior is implementation-defined before C99 (arithmetic vs. logical shift of the sign bit), but modern C compilers follow two's complement — −5 << 1 = −10, consistent with the multiply rule.

Shift example with binary representation — 5 << 2:

5 = 0000 0101 (binary) 5 << 1 = 0000 1010 (shift left 1) = 10 5 << 2 = 0001 0100 (shift left 2) = 20 5 << 3 = 0010 1000 (shift left 3) = 40

Each shift moves the bits one position to the left and fills the rightmost bit with 0. The value doubles with each shift.

Complete C Program

Here is the program — left shift an integer by a specified count:

Program: Left 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 iterates from bit 7 down to bit 0, using (n >> i) & 1 to isolate each bit. This displays the binary representation before and after the shift, making the "left shift = multiply by 2" rule visually obvious.

Program Output

Sample run of the basic program:

Enter a number and a shift count: 5 2
5 << 2 = 20
                            

5 × 22 = 5 × 4 = 20 — correct.

More examples:

Enter a number and a shift count: 1 10
1 << 10 = 1024
                            

210 = 1024 — the classic "compute a power of 2 by shifting 1."

Enter a number and a shift count: 255 1
255 << 1 = 510
                            

255 × 2 = 510 — same result, from a very different bit pattern.

The variant with binary display:

Enter a number (0-255) and shift count (0-7): 5 2

n         = 0000 0101
n << 2    = 0001 0100

Decimal result: 20
                            

The binary view makes it clear: the bits of 5 (0000 0101) moved two positions left, filling zeros on the right, producing 0001 0100 = 20.

Edge case — overflow when shifting too far:

Enter a number and a shift count: 16777216 8
16777216 << 8 = 0
                            

16777216 = 224. Shifting it left by 8 gives 232, which is exactly 1 beyond the maximum representable value of a 32-bit int — so the result wraps to 0 (all bits shifted off the left edge, zeros fill in on the right). This is a form of overflow, technically undefined behavior for signed integers, but on two's-complement systems it produces 0.

Step-by-Step Explanation

1. Declarations: int n, k; — n is the value to shift, k is the shift count. Both are integers. The shift operator works on any integer type.

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, including garbage or a crash. Always validate before shifting.

3. The shift operation: n << k moves each bit of n left by k positions. Each left shift multiplies the value by 2 (with wraparound if it overflows). 5 << 2 = 20 because 5 × 2² = 20.

4. Binary view: For 5 << 2:

  • 5 in binary: 0000 0101
  • Shift left by 2: 0001 0100 (each bit moves 2 positions left; the two rightmost bits become 0)
  • 0001 0100 = 20 in decimal

5. Signed vs unsigned: The behavior of << on signed integers with the sign bit set is undefined in the C standard (pre-C++20/C23 clarifications). On all modern compilers with two's complement, −1 << 1 gives −2 (arithmetic shift preserving sign), consistent with the multiply rule. For strict portability, use unsigned int for bit manipulation — the standard fully specifies shift behavior for unsigned types (no sign bit, no surprises).

6. Overflow: Shifting left past the type's width drops the high bits. 2,147,483,648 << 1 for int gives 0 (the only set bit (bit 31) is shifted off). This is undefined behavior for signed integers, but the multiply rule "wraps" predictably on two's-complement hardware.

7. Practical uses: 1 << k produces a mask with only bit k set — this is the standard way to test, set, or clear individual bits. n << 3 is a fast multiply by 8. Combining with OR builds bit patterns: (RED << 16) | (GREEN << 8) | BLUE packs three color bytes into one integer.

🎯 Key idea: n << k shifts bits left, multiplying by 2k. Bits shifted off the left are lost; zeros fill in on the right. Always validate the shift count (0 ≤ k < bit-width) — negative or excessive shifts are undefined behavior. Use 1 << k to build bit masks.

Frequently Asked Questions

1. Why is n << k the same as n × 2k?

Because in binary, shifting a value left by 1 doubles it — every bit moves to a position worth twice as much. Shifting by 2 multiplies by 4, shifting by 3 multiplies by 8, and so on. This is exactly the same as multiplying by 2k. The identity holds as long as the result doesn't overflow the type. This is why left shift is often used as a fast multiply-by-power-of-2.

2. What happens if I shift by a count ≥ the bit width?

It's undefined behavior in C — anything can happen, including a garbage result, a crash, or a "helpful" compiler diagnostic. 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. The bit-width is sizeof(type) * CHAR_BIT, usually 32 for int and 64 for long long.

3. What about shifting negative numbers?

Shifting a negative signed integer left is undefined in the C standard (specifically, the sign bit and shift behavior on negative numbers are implementation-defined until C23 clarifies some cases). On virtually all modern compilers (two's complement), −5 << 1 = −10, following the multiply rule. For fully portable code, use unsigned int for bit manipulation — shifting unsigned integers is fully specified (it's modular arithmetic).

4. How do I create a bit mask?

Use 1 << k to get a mask with only bit k set. To check if a bit is set: if (n & (1 << k)). To set a bit: n |= (1 << k). To clear a bit: n &= ~(1 << k). To toggle a bit: n ^= (1 << k). The shift operator builds the mask; the bitwise operators apply it. To combine masks, OR them: (1 << 3) | (1 << 5).

5. Is n * 2 faster than n << 1?

In modern code, the compiler usually generates the same machine instruction (or better) for both. The multiplication 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 (masking, flag setting). Never use << just to "save cycles" — the compiler knows what it's doing. Both forms are idiomatic in different contexts.

💡 Tip: once this works, try these classic left shift applications: (a) compute powers of 2 (1 << k), (b) build color values ((r << 16) | (g << 8) | b), (c) set bits (n |= (1 << k)), (d) fast multiply by powers of 2 (n << k), (e) construct hash multipliers (hash * 31 is often written (hash << 5) - hash in older C code). Each is a small extension of the same operator.

📖 Related Tutorials

  • Previous: Bitwise XOR on Two Numbers Using '^'
  • Next: Bitwise Right Shift Using '>>'
  • Check Even/Odd Using Bitwise AND
  • Toggle a Particular Bit Using XOR
  • Bitwise Operators in C — Full Tutorial
  • All 15 Operator Assignments in C
  • Operators FAQ

Previous Topic: -->> 8. Bitwise XOR on Two Numbers Using the '^' Operator   ||   Next Topic: -->> 10. Bitwise Right Shift on a Number Using the '>>' Operator


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.