Convert to N-bit Integer

by Ricardo Fernández Serrata

Version 1 (November 26, 2021)

Download (0 downloads)

Keep the bits intact, change the numerical value, as if you were using actual integers.

Converts the truncated input number into the value it would have as an unsigned or signed b-bit integer.

If `b` is negative, converts to signed, otherwise unsigned.

If `b >= -32 && b < 32`, it makes any value safe to use with bitwise operators and functions like hexEncode() and ctz(), because AM clamps instead of wrapping-around.

This algorithm is based on Ecmascript's integer-conversion algorithms:
https://tc39.es/ecma262/#sec-toint32
https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-bigint.asintn