Question

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

Was it helpful?

Solution

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.

OTHER TIPS

From my (second) reading of your question, it doesn't seem as if you need to "extract" any bits, but rather convert the whole number?

I.e. do something like this:

int negative = -4711;
short x = (short) negative;

In this case, the compiler will make sure that as much as possible of the original number's precision gets converted in the assignment. This would be the case even if the underlying hardware was not using 2:s complement. If it is, then this is likely to just be a truncation, as explained by Motti.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top