help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Bit shift by more than word length


From: Bernd Strieder
Subject: Re: Bit shift by more than word length
Date: Thu, 14 Jun 2007 15:41:14 +0200
User-agent: KNode/0.10.4

Hello,

Lionel B wrote:

> Hi,
> 
> If x is of (unsigned) integer type of size N then the C++ standard
> says that x << n and x >> n are undefined for n >= N. Is there by any
> chance a GNU extension that guarantees that at least x << N and x >> N
> are defined (and = 0)?

Most compilers will create code using the assembler codes for shifting
available on the hardware, which usually do something like x << (n%N),
i.e. shifting by a modulus, which is obtained in binary by truncating
the shift value. Anything else would already require testing and
possibly branching by the compiler. I have never programmed on a CPU
where this is different. 

Maybe the branch can be optimized away by means of conditional
statements. You might have to experiment with the architecture and CPU
model options of gcc to get there.


#include <stdio.h>

int main(int argc)
{
    int i, j;
    for(i = 0; i < 64; ++i) {
        j = 1<<i;
        if (i & ~31) j = 0;
        printf("%d %d\n",i, j);
    }
}

Indeed, when looking at the result of this using gcc-4.1.2 there is no
branch generated for the if to maintain the zero, at least
with -march=i686 or -march=opteron, there is a branch
with -march=pentium3. So double check gcc behaves the same way on your
platform, otherwise you are hunting a phantom problem, and measure,
whether on that platform a branch is preferable.

Bernd Strieder



reply via email to

[Prev in Thread] Current Thread [Next in Thread]