Satachito
Satachito

Reputation: 5888

JavaScript's addition result in weird result

I have encountered strange phenomeon while calculating some checksum. So I reduced this problem into small script.

% node
Welcome to Node.js v16.1.0.
Type ".help" for more information.
> console.log( ( 0x20000026c6db24 + 0x8bf8a215 ).toString( 16 ) )
200000b2bf7d38

In Safari and Chrome.

<script>
console.log( ( 0x20000026c6db24 + 0x08bf8a215 ).toString( 16 ) )
</script>

Browser's console
200000b2bf7d38

I think it must be 200000b2bf7d39. Please let me know why this calculation result in 200000b2bf7d38.

Upvotes: 1

Views: 62

Answers (1)

Alexander Alexandrov
Alexander Alexandrov

Reputation: 1372

This is because you use the wrong type. JS Number can not be treated as a fixed nor floating-point. But such a big numbers 0x20000026c6db24 > Number.MAX_SAFE_INTEGER can not be used safely in the context of fixed-point calculations. But BigInt could be used explicitly:

(BigInt('0x20000026c6db24') + BigInt('0x8bf8a215')).toString(16) // '200000b2bf7d39'

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/BigInt

Upvotes: 2

Related Questions