Faster multiplication or division by powers of 2

suggest change

Shifting bits left (right) is equivalent to multiplying (dividing) by 2. It’s the same in base 10: if we “left-shift” 13 by 2 places, we get 1300, or 13 * (10 ** 2). And if we take 12345 and “right-shift” by 3 places and then remove the decimal part, we get 12, or Math.floor(12345 / (10 ** 3)). So if we want to multiply a variable by 2 ** n, we can just left-shift by n bits.

console.log(13 * (2 ** 6)) //13 * 64 = 832
console.log(13    <<   6)  //          832

Similarly, to do (floored) integer division by 2 ** n, we can right shift by n bits. Example:

console.log(1000 / (2 ** 4)) //1000 / 16 = 62.5
console.log(1000    >>   4)  //            62

It even works with negative numbers:

console.log(-80 / (2 ** 3)) //-80 / 8 = -10
console.log(-80      >> 3)  //          -10

In reality, speed of arithmetic is unlikely to significantly impact how long your code takes to run, unless you are doing on the order of 100s of millions of computations. But C programmers love this sort of thing!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Bitwise operators:
* Faster multiplication or division by powers of 2

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
19 Bitwise operators
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde