64bit integer in Javascript

Viewed 42

I saw this question on CodeSignal where the return type was supposed to be an array of 64-bit integers. Here's an example return value:

[23, 34, 65]

The default size of number in JavaScript is 64-bit, which is a decimal value with 53-bit mantissa.

Also, I tried this:

BigInt.UintN(64, 32n)

This too threw the same error as Type mismatch. I am looking for the right way to convert a number to 64-bit integer — or is this a limitation of the language and I should simply not do algorithms in JavaScript?

2 Answers

According the documentation to converting number to int64

While we want to convert any number to 64bit integer, we need to write

// Require, of course
> Int64 = require('node-int64')

// x's value is what we expect (the decimal value of 0x123456789)
> x = new Int64(0x123456789)
//and the value of x, is
[Int64 value:4886718345 octets:00 00 00 01 23 45 67 89]

Hope it was helpful. Thank you

The requirements are a bit ambiguous. The "example return value" is simply an array of numbers, which will not be able to hold a full 64-bit integer, so that looks contradictory to what the wording of the requirement is.

In case the example value is wrong and the requirement is correct, there is still some ambiguity.

It could be that they were expecting a typed 64-bit integer array (BigInt64Array):

new BigInt64Array([23n, 34n, 65n])

(It's also unclear whether signed or unsigned integers are desired. In case of unsigned, BigUInt64Array would be needed instead.)

It could also be that they were simply expecting an array of BigInt values:

[23n, 34n, 65n]

Or, of course, maybe the requirements are misleading and the example return value is correct, in which case regular numbers are expected (unable to hold 64-bit integers without loss of precision):

[23, 34, 65]

Or, perhaps, the requirement is simply to clamp the value to 64 bits and discard the overflow, in which case you'd have to use BigInt.asIntN:

function clamp (array) {
  return array.map(n => BigInt.asIntN(64, n))
}

(In case unsigned integers are expected, you'd need BigInt.asUIntN instead.)

This would however assume an array of BigInts as input and would also output BigInts, so it would again not match the shown example return value which had regular numbers.

In summary, it seems that the question is either wrong in itself (either in its wording or in its example) or it may be simply impossible to do in JavaScript. There is not enough information provided to give a definite answer.

Related