Wrap into an integer type
ExactA number brought into the range of SINT, INT, DINT and the other integer types.
v mod 2ⁿ, moved into the signed range
The value is cut toward zero, reduced modulo 2ⁿ and moved into the signed range, all without rounding for types up to 32 bits. Types of 53 bits or more are returned unwrapped, so a 64-bit integer is exact only while it stays below 2⁵³.
/** Wrap a number into an integer type (two's complement). 64-bit types are held as doubles: exact to 2^53, said in the docs. */
export function wrapInt(type, v) {
const spec = INT_TYPES[type]; v = Math.trunc(v);
if (!spec || !Number.isFinite(v)) return Number.isFinite(v) ? v : 0;
const [bits, signed] = spec; if (bits >= 53) return v;
const mod = 2 ** bits; v = ((v % mod) + mod) % mod;
return signed && v >= mod / 2 ? v - mod : v;
}