Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

JavaScript integer shift safety: (n << 1) != (n * 2)

Digging JS just discovered something new to me:

n = 0xffffffff
4294967295
n
4294967295
n << 1
-2
n * 2
8589934590
(n << 1) == (n * 2)
false
n + 1
4294967296

This is console output of builtin FireFox (51.0.1 64-bit) debugger...

What I have read so far (w3school, etc), does not allow me to suspect such a behaviour.

Is it ok or have I something missed?

...To be continued...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

n << b handles n and the result as int 32, whereas n * 2 handles n and the 2 as number.

Note that 4294967295 << 0 will be -1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...