问题
While solving my previous question I faced even more funny thing.
Try integer math (yes, I know they aren't "too integer" inside) to see how much bits are available:
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
So, how many bits are available for JS-style integer math now?
Tested in FireFox 51 64-bit debugger.
A bit more illustrations after the answer:
var n = 0xffffffffffffffff;
for(var i=1; i<=1024*1024; i*=2){
console.log('i='+i+'; v='+(n/i-1).toString(16));
}
/* Output:
i=1; v=10000000000000000
i=2; v=8000000000000000
i=4; v=4000000000000000
i=8; v=2000000000000000
i=16; v=1000000000000000
i=32; v=800000000000000
i=64; v=400000000000000
i=128; v=200000000000000
i=256; v=100000000000000
i=512; v=80000000000000
i=1024; v=40000000000000
i=2048; v=1fffffffffffff
i=4096; v=fffffffffffff
i=8192; v=7ffffffffffff
i=16384; v=3ffffffffffff
i=32768; v=1ffffffffffff
i=65536; v=ffffffffffff
i=131072; v=7fffffffffff
i=262144; v=3fffffffffff
i=524288; v=1fffffffffff
i=1048576; v=fffffffffff
*/
回答1:
Your calculations aren't correct, because just because integer n exist, doesn't mean that every integer smaller than n exists. Maximum safe integer is 2^53 - 1
So the correct answer is: 53 bits.
Number.MAX_SAFE_INTEGER
来源:https://stackoverflow.com/questions/42223542/how-many-bits-are-available-for-js-style-integer-math-now