How to perform the bitwise left-shift operation in Swift

Overview

The bitwise left-shift operation in Swift moves the bits of a number towards the left according to a given integer value. The vacant space is then occupied by a 0. It is represented by <<.

Syntax

number << a

Parameters

  • number: This is the value on which the bitwise operation is being performed.
  • a: This is the integer that dictates how many times the bits will shift to the left.

Return value

The bitwise left shift operation (<<) returns a number that is equivalent to multiplying the input value by a factor of 2. For example, shifting the bits of an integer to the left once results in double the value (or 212^{1}). The generalized formula is number2anumber*2^ a .

Example

// the number on which left shift will be applied
var number = 20 // binary : 10100
// the number of shifts
var shift = 3
var result = 20 << 3
print(result) // 160. binary : 10100000

Explanation

  • Line 2: We initialize the number variable, which holds the value on which the left shift will be applied.
  • Line 5: We initialize the shift variable, which is the number of left shifts to be applied.
  • Line 7: We perform the left shift operation and store the result in the result variable. We can confirm our answer by the following: 2023=208=16020*2^{3}=20*8=160
Representing the left shift operation applied on the number (20) diagrammatically

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved