Frage

According to text: "In rare case of C/C++ compiler that does not perform sign extension on right shift of a negative number, the trick to shift right to divide the number fails"

Consider the following example:

unsigned int i = 0b10000000; // 128
i = i >> 1; // i equals 01000000 i.e. 64 

That is the only way I know to block sign extension. Also, by adding unsigned it becomes a positive number so please correct.

War es hilfreich?

Lösung

Sign extension on bitwise right-shift of negative number is implementation-defined in C. It means it is up to the compiler to decide if it performs the sign propagation and the compiler documentation has to document the selected behavior.

From the C Standard:

(C99, 6.5.7) "If E1 has a signed type and a negative value, the resulting value is implementation-defined."

Among compilers, gcc always propagates the sign:

Signed `>>' acts on negative numbers by sign extension.

http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top