I have signed numbers (2s complement) stored in 32-bit integers, and I want to extract 16-bit fields from them. Is it true that if I extract the low 16 bits from a 32-bit signed number, the result will be correct as long as the original (32-bit) number fits into 16 bits ?
For positive numbers it is trivially true, and it seems that for negatives as well. But can it be proven ?
Thanks in advance
Yes, in two's complement the sign bits extend "all the way" to the left. When you cast a signed short to a signed int then the number is "sign extended" and has the same value.
Example: Nibble
(-2) = 1110 => Byte(-2) = 1111_1110
Obviously the opposite it true too, if you capture at least one sign bit then the value of the number remains unchanged.