www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Problems with shift left operator (dmd 0.169)

reply KlausO <oberhofer users.sourceforge.net> writes:
Hello D-experts,

I created a little test program which IMHO shows
not the expected behaviour.
Is this a bug or not ?

module testshift;

import std.stdio;

void main()
{
   uint val_a = (1 << 32);

   uint shift = 32;
   uint val_b = (1 << shift);

   writefln("Result: ", val_a, "  ", val_b);
   assert(val_a == val_b);
}

Output is as follows:
Result: 0  1
Error: AssertError Failure testshift(14)
Oct 10 2006
parent reply Lionello Lunesu <lio lunesu.remove.com> writes:
KlausO wrote:
 Hello D-experts,
 
 I created a little test program which IMHO shows
 not the expected behaviour.
 Is this a bug or not ?
 
 module testshift;
 
 import std.stdio;
 
 void main()
 {
   uint val_a = (1 << 32);
 
   uint shift = 32;
   uint val_b = (1 << shift);
 
   writefln("Result: ", val_a, "  ", val_b);
   assert(val_a == val_b);
 }
 
 Output is as follows:
 Result: 0  1
 Error: AssertError Failure testshift(14)
The problem here is: what values would you expect? 1<<32 is too big for an uint, so the 0 from the constant folding is correct, BUT the "shl" instructions (the one << translates into) only looks at the lower 5 bits, which are 0 (32 & 0x1F == 0), so also the 1 is correct. I don't think we'd want extra overhead for something like <<, so I suppose we let "<<" behave like the instruction "shl". Which means there's only one solution: let the compiler complain. Come to think of it, it should already have complained: 1<<32 does not fit into an uint! But DMD gives no error, not even a warning (-w)... L.
Oct 10 2006
parent reply Frank Benoit <keinfarbton nospam.xyz> writes:
http://www.digitalmars.com/d/expression.html#ShiftExpression
It's illegal to shift by more bits than the size of the quantity being
shifted.

That means, 32 is legal for shifting. And therefore it should evaluate
to the correct result.

So I think the example is a bug.
Oct 11 2006
parent reply Lionello Lunesu <lio lunesu.remove.com> writes:
Frank Benoit wrote:
 http://www.digitalmars.com/d/expression.html#ShiftExpression
 It's illegal to shift by more bits than the size of the quantity being
 shifted.
 
 That means, 32 is legal for shifting. And therefore it should evaluate
 to the correct result.
 
 So I think the example is a bug.
I think 32 should be illegal also. It would append 32 0-bits, which means the result (uint) will always be 0. L.
Oct 11 2006
parent KlausO <oberhofer users.sf.net> writes:
Lionello Lunesu wrote:
 
 I think 32 should be illegal also. It would append 32 0-bits, which 
 means the result (uint) will always be 0.
 
Are there practical uses for shifting more than 32 bits ? Example: Calculating a mask uint mask = (1 << nbits) - 1; Of course, you could express this also as uint mask = (0xffffffff >> (32 - nbits));
Oct 11 2006