JavaScript 的加法结果很奇怪
JavaScript's addition result in weird result
我在计算一些校验和时遇到了奇怪的现象。所以我把这个问题简化成小脚本。
% node
Welcome to Node.js v16.1.0.
Type ".help" for more information.
> console.log( ( 0x20000026c6db24 + 0x8bf8a215 ).toString( 16 ) )
200000b2bf7d38
在 Safari 和 Chrome.
<script>
console.log( ( 0x20000026c6db24 + 0x08bf8a215 ).toString( 16 ) )
</script>
Browser's console
200000b2bf7d38
我想一定是200000b2bf7d39。请告诉我为什么这个计算结果是 200000b2bf7d38。
这是因为你用错了类型。 JS Number 不能被视为定点或浮点数。但是这么大的数字 0x20000026c6db24 > Number.MAX_SAFE_INTEGER
在定点计算的上下文中不能安全使用。
但是 BigInt
可以显式使用:
(BigInt('0x20000026c6db24') + BigInt('0x8bf8a215')).toString(16) // '200000b2bf7d39'
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/BigInt
我在计算一些校验和时遇到了奇怪的现象。所以我把这个问题简化成小脚本。
% node
Welcome to Node.js v16.1.0.
Type ".help" for more information.
> console.log( ( 0x20000026c6db24 + 0x8bf8a215 ).toString( 16 ) )
200000b2bf7d38
在 Safari 和 Chrome.
<script>
console.log( ( 0x20000026c6db24 + 0x08bf8a215 ).toString( 16 ) )
</script>
Browser's console
200000b2bf7d38
我想一定是200000b2bf7d39。请告诉我为什么这个计算结果是 200000b2bf7d38。
这是因为你用错了类型。 JS Number 不能被视为定点或浮点数。但是这么大的数字 0x20000026c6db24 > Number.MAX_SAFE_INTEGER
在定点计算的上下文中不能安全使用。
但是 BigInt
可以显式使用:
(BigInt('0x20000026c6db24') + BigInt('0x8bf8a215')).toString(16) // '200000b2bf7d39'
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/BigInt