rbwhitaker / CSharpPlayersGuideEarlyAccess

A place to track issues with the C# Player's Guide for patches and future editions
19 stars 0 forks source link

The unsigned right shift operator `>>>` #648

Closed rbwhitaker closed 1 year ago

rbwhitaker commented 2 years ago

>> is a right shift.

I don't know that I totally understand this one right now, and I'm wondering if there's a typo in the example here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators#unsigned-right-shift-operator-

But the idea is that >>> does a logical shift instead of the arithmetic shift that >> does.

This is, apparently, not an issue with left shifting.

rbwhitaker commented 1 year ago

This was a tricky one. To just talk about >>> isn't crazy hard. But the nuanced differences between >> and >>> are complex. For unsigned types, they're identical. For positive numbers of signed types, they're identical. In all those cases, the empty holes from shifting are filled with zeroes. But when you right shift a negative value of a signed type, there are two different strategies. One is to fill with zeroes and the other is to fill with more of whatever used to be in the leftmost bit. Filling with zeroes makes sense when you're just looking at the thing as a pile of bits. Filling with the leftmost bit is useful when you're using bit shifting as a clever way to do arithmetic. (Specifically, x >> 1 is the same as dividing by two, x >> 2 is the same as dividing by four, and x << 1 is the same as multiplying by two, and x << 2 is the same as multiplying by four.) >> is for the arithmetic shift, which is used to divide by powers of two, etc., while >>> is for bitwise right shifting, when you're considering the values just as a pile of bits.

And there, I just explained it a whole lot better than is currently even in the book, or in the blog posts. :D Now I need to do some revising!