delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/05/12/10:57:40

From: Hans-Bernhard Broeker <broeker AT physik DOT rwth-aachen DOT de>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Right shift
Date: 12 May 2000 14:35:42 GMT
Organization: Aachen University of Technology (RWTH)
Lines: 26
Message-ID: <8fh4ru$j2l$1@nets3.rz.RWTH-Aachen.DE>
References: <391C0409 DOT 79567772 AT tiscalinet DOT it>
NNTP-Posting-Host: acp3bf.physik.rwth-aachen.de
X-Trace: nets3.rz.RWTH-Aachen.DE 958142142 19541 137.226.32.75 (12 May 2000 14:35:42 GMT)
X-Complaints-To: abuse AT rwth-aachen DOT de
NNTP-Posting-Date: 12 May 2000 14:35:42 GMT
Originator: broeker@
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019