问题
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...
回答1:
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
.
回答2:
In javascript, right shift operator or left shift operator only support 32 bit. 2 ^32 - 1 = 4294967295.
回答3:
The first comment has answered the question: bitwise ops are 32-bit signed.
The math looks to be way longer:
var n = 0xffffffff;
// loop over 1P:
for(var i=1; i<=1024*1024*1024*1024; i*=16) {
var v=(n*i).toString(16);
console.log('i='+i+'; v='+v+' ('+v.length*4+')');
}
// Output:
// i=1; v=ffffffff (32)
// i=16; v=ffffffff0 (36)
// i=256; v=ffffffff00 (40)
// i=4096; v=ffffffff000 (44)
// i=65536; v=ffffffff0000 (48)
// i=1048576; v=ffffffff00000 (52)
// i=16777216; v=ffffffff000000 (56)
// i=268435456; v=ffffffff0000000 (60)
// i=4294967296; v=ffffffff00000000 (64)
// i=68719476736; v=ffffffff000000000 (68)
// i=1099511627776; v=ffffffff0000000000 (72)
// i=17592186044416; v=ffffffff00000000000 (76)
// i=281474976710656; v=ffffffff000000000000 (80)
I.e. at least 80 bits are available... He-he!
You'll get an "immutable number" quite soon!
n=0xffffffffffffffff // 64-bit wanted
18446744073709552000 // what? even decimal for odd hex?
n.toString(16)
"10000000000000000" // ooops...
n-1
18446744073709552000
n-2
18446744073709552000
n-4
18446744073709552000
It looks like it should be a separate question...
来源:https://stackoverflow.com/questions/42221373/javascript-integer-shift-safety-n-1-n-2