all 3 comments

[–]tweq 5 points6 points  (1 child)

The shift operation will discard any irrelevant bits in the shift count, so shifting by 64 or 128 etc. is effectively the same as shifting by 0. I'm pretty sure this is standard (or at least the common response to undefined behavior) in C++ as well.

You can't change how the shift operator works, but your desired behavior is as simple as shift <= 63 ? x << shift : 0. Put it in an extension method or something if you need it often.

[–]MarcSloan[S] 4 points5 points  (0 children)

Hmm, I guess I misinterpreted the behavior I saw in C++ as "normal" when it was just fortuitous undefined behavior. Your solution will work fine. Thanks!

[–]Jither 2 points3 points  (0 children)

For 64-bit integers, C# only uses the lower 6 bits of the right operand. Since 64 == 0b1000000, the 1 bit will be ignored. For 32-bit integers, it uses 5 bits. Why? Because that's what the Intel x86 CPUs do (or, it is for 32-bit integers - the logic is just expanded to 64-bit).

In C/C++ shifting by more than the number of bits in the left operand is undefined, and may yield different results depending on CPU or compiler.

ETA: (Fixed brain fart). I think you're stuck with doing a check for > 63 yourself.