Brian Ogden
Brian Ogden

Reputation: 19232

Shifting bits left to achieve exponentiation to the power of two Javascript

Say I have the following:

var n = 3;

I want 2^n power.

So I can do:

Math.pow(2,n)

That equals 8, sweet.

Or I could do:

1 << n

That also equals 8, sweet.

I am trying to picture the shift of bits.

So I think n's, which equals 3 in this example, binary notation is:

11

That is (1 * 2^1) + (1 * 2^0) = 3

So then I do the operation 1 << n and the bits shift left ONE, I think the output of 1 << n, in binary notation, is this:

110

The bits shift left one position, replacing the first bit with zero BUT this equals 6 not 8:

That is (1 * 2^2) + (1 * 2^1) + (0 * 2^0) = 6

Not sweet, after the bit shift left I am calculating that 1 << n would equal six based on my binary notation, 1 << n does equal 8 so my binary notation of the left bit shift manipulation is incorrect

Either I am drafting the binary notation of 3 incorrectly and/or I am not shifting the bits left correctly in my binary notation for the output of 1 << n

Could anyone provide an explanation to where my thought processes are incorrect?

Upvotes: 1

Views: 1034

Answers (1)

Oriol
Oriol

Reputation: 288590

1 << n means: add n zeros at the end of the binary representation of 1.
That produces 1 * 2ⁿ = 2ⁿ. In your case, 2³ = 8 = 10002.

n << 1 means: add 1 zeros at the end of the binary representation of n.
That produces n * 2¹ = 2*n. In your case, 2*3 = 6 = 1102.

Therefore, the problem is that you confused 1 << n and n << 1.

Upvotes: 4

Related Questions