i try to get 3 ranges between 2 bigint values in nodejs. My current code looks like:
var start = -9223372036854775807;
var end = 9223372036854775807;
var steps = (end - start) / 3;
console.log(start);
for (let xx = 0; xx < 3; xx++) {
end = start + steps;
console.log(`${start} - ${end}`);
start = start + steps;
}
but this is already incorrect, the output looks like:
-9223372036854776000
-9223372036854776000 - -3074457345618259000
-3074457345618259000 - 3074457345618258000
3074457345618258000 - 9223372036854775000
the final result should be 3 steps in a range of -9223372036854775807 and 9223372036854775807
any hints why node is cutting the last digest ?
You need to declare all your numbers as BigInt values with the n
suffix including the 3n
. Without that suffix, these are just being treated as regular values (no BigInt values) and you're overflowing what they can contain.
let start = -9223372036854775807n;
let end = 9223372036854775807n;
let steps = (end - start) / 3n;
console.log(`before loop: start = ${start}, steps = ${steps}`);
for (let xx = 0; xx < 3; xx++) {
end = start + steps;
console.log(`in loop: start = ${start}, end = ${end}`);
start = start + steps;
}
Please note that because your start
value is negative and you're calculating steps as (end - start) / 3n
, you're going to get a very large number for the steps. I'm not entirely sure this is really what you intended, but this code will do the proper BigInt math on the numbers you specified.