0

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 I'm not sure 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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
hippietrail
  • 15,848
  • 18
  • 99
  • 158
  • 1
    Just take the high 32-bit and & with `~((1 << 21) - 1)` to check if there is any bit over the limit. – nhahtdh Dec 24 '12 at 12:28
  • D'oh! I was thinking it involved multiplication so somehow I must have to take into account both pieces... but now I realize only the high piece is multiplied so of course I only have to check the high piece! This still might be useful to other readers with a similar mental block though (-: – hippietrail Dec 24 '12 at 12:32

1 Answers1

2

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.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
nhahtdh
  • 55,989
  • 15
  • 126
  • 162