Bit shift question.

  • Thread starter Thread starter Ken Varn
  • Start date Start date
K

Ken Varn

I am seeing a discrepancy on how bit shifts work in C# vs. C++. In C++, if
you do a bit shift and it overflows, the bits are lost.

i.e. in C++, -1 << 32 would produce 0. However, in C#, this same expression
yields -1.


Is there anyway to have C# bit shift behave like C++?


--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------
 
Is there anyway to have C# bit shift behave like C++?

Well, actually, it is. Sorta. Bit's shifted off the left ARE lost.
print -1 << 31 and you'll see that. The problem is that C# since
shifting a 32-bit number 32 bits is undefined, C# executes "a << b" as
if it were written "a << (b & 31)".
 
Bitshifting by more than (n bits-1) is unspecified in c++ standard, so
different compilers may implement it in different ways and different
platforms may react different on this.

So you have to make sure that your shift count lies in the range of 0 to 31.

Iam not sure, but using a cast to uint may solve your problem in C#, though.
 
Well, actually, it is. Sorta. Bit's shifted off the left ARE lost.
print -1 << 31 and you'll see that. The problem is that C# since
shifting a 32-bit number 32 bits is undefined, C# executes "a << b" as
if it were written "a << (b & 31)".

And if compiler recognises that the number of steps would be zero, the
shift is optimized away. "-1 << 32" executes as if it were written "-1".

:)
 
Back
Top