How to use Bitwise Left Shift operator in Javascript

Description

The left shift is represented by two less-than signs << and shifts all bits in a number to the left by the number of positions given.

Example

For example, if the number 2 (which is equal to 10 in binary) is shifted 5 bits to the left, the result is 64 (which is equal to 1000000 in binary), as shown here:


var oldValue = 2;             //equal to binary 10
var newValue = oldValue << 5; //equal to binary 1000000 which is decimal 64
console.log(newValue);

The left shift fills bits with 0s to make the result a complete 32-bit number.

Note that left shift preserves the sign of the number it's operating on. For instance, if -2 is shifted to the left by five spaces, it becomes -64, not positive 64.

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions