Mail Archives: djgpp/2000/05/12/10:57:40
night DOT walker AT tiscalinet DOT it wrote:
> Why right-shifting ">>" a negative signed int will first turn it
> positive?
Wrong question, sort of.
The behaviour of bitshift operations on negative integers is
purposefully left implementation-defined by the C language definition.
For short, that means you should not assume anything about the way it
works. Bitshifting never was meant to be used for numbers (integers of
any kind), really, it's for collections of bits.
If you wanted / 2, write /2, not >>1. Trust your compiler to
automatically translate that as >>1 if that's a safe and fast method
for the case at hand. If you think you cannot trust your compiler even
that far: why aren't you using a better one?
It's better for your programming skills if you do not know how this is
implemented, so you don't make any silent assumption that will break
if your program ever gets moved to another compiler, operating system
or machine. Ignorance can protect you, sometimes.
--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.
- Raw text -