How to guard against too-large values when creating a 64-bit integer from high and low 32-bit parts in JavaScript?

StackOverflow https://stackoverflow.com/questions/14021369

Domanda

So JavaScript integers are interally 64-bit floating values and hence can precisely support values from -253 to +253 (-9,007,199,254,740,992 to +9,007,199,254,740,992).

You can read all about it in our very interesting thread: What is JavaScript's Max Int? What's the highest Integer value a Number can go to without losing precision?

In my project I need 64-bit offsets into very large files. I can make these by combining a high and low pair of 32-bit values. I don't need the full 64-bit range so JavaScript's limits are fine.

But what I'm not sure how to do is how to sanity-check that a given pair of 32-bit values wouldn't result in a number outside JavaScript's range.

How could I check against this? I assume it might be trickiest for numbers just outside this range.

È stato utile?

Soluzione

We only need to check if there is any ON bit higher than the 53rd bit, or higher than the 21st bit of the high 32-bit part.

Just take the high 32-bit and & with ~((1 << 21) - 1) (this will clear all the lower 21-bit of the 32-bit) to check if there is any bit over the limit. The number will be inside the limit if the result is 0.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top