toSigned abstract method

int toSigned(
  1. int width
)

Returns the least significant width bits of this integer, extending the highest retained bit to the sign.

This is the same as truncating the value to fit in width bits using a signed two's complement representation. The returned value has the same bit value in all positions higher than width.

                         //     V--sign bit-V
16.toSigned(5) == -16;   //  00010000 -> 11110000
239.toSigned(5) == 15;   //  11101111 -> 00001111
                         //     ^           ^

This operation can be used to simulate arithmetic from low level languages. For example, to increment an 8 bit signed quantity:

q = (q + 1).toSigned(8);

q will count from 0 up to 127, wrap to -128 and count back up to 127.

On JavaScript platforms, only the least significant 32 bits are used, and width is effective up to 32 bits (if width is greater than 32, the least significant 32 bits are returned as an unsigned 32-bit integer). On native platforms, the 64-bit signed integer is used directly, and width values of 64 or greater return this unchanged.

If the input value fits in width bits without truncation (up to 64 bits on native platforms, or 32 bits on JavaScript platforms), the result is the same as the input. The minimum width needed to avoid truncation of x within that range is x.bitLength + 1, i.e.

x == x.toSigned(x.bitLength + 1);

Implementation

int toSigned(int width);