signExtend method
Returns this
sign-extended to endSize
bits.
Sign extension is the operation of increasing the number of bits of a
binary number while preserving the number's sign. This is done by
appending digits to the most significant side of the number, i.e. if 6
bits are used to represent the value 00 1010
(decimal +10) and the sign
extend operation increases the word length to 16 bits, the new
representation is 0b0000 0000 0000 1010
.
Simiarily, the 10 bit value 11 1111 0001
can be sign extended to 16-bits
as 1111 1111 1111 0001
. This method is provided as a convenience when
converting between ints of smaller sizes to larger sizes.
Implementation
int signExtend(int startSize, int endSize) {
if (endSize <= startSize) {
throw RangeError.value(
endSize,
'endSize',
'Expected endSize ($endSize) <= startSize ($startSize).',
);
}
if (isClear(startSize)) {
return bitRange(startSize, 0);
} else {
final mask = endSize == 32 ? 0xffffffff : (1 << endSize) - 1;
final bits = this | (mask & ~((1 << startSize) - 1));
return bits < 0 ? bits + 0x100000000 : bits;
}
}