Bit shift question.

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
-----------------------------------
 
J

james.curran

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)".
 
C

cody

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.
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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".

:)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top