I underestimated the complexity of the >> operator; it’s not doing what I thought it would.
I want to right shift a uint value of 6542454. I thought it worked like this:
val (is) == 11000111101010001110110
val >> 1 == 1100011110101000111011
val >> 2 == 110001111010100011101
val >> 3 == 11000111101010001110
val >> 4 == 1100011110101000111
val >> 5 == 110001111010100011
val >> 6 == 11000111101010001
val >> 7 == 1100011110101000
In reality, the results are:
val >> 1 == 1100011110101000111011
val >> 2 == 110001111010100011101
val >> 3 == 11111001100100110010011
val >> 4 == 1111100110010011001001
val >> 5 == 111110011001001100100
val >> 6 == 11111001100100110010
val >> 7 == 10011011111110111111100
The 3rd operation clearly does something I don’t understand and things go off the rails from there. Seems to do the thing I don’t understand again at the 7th operation as well.
Using the >>= operator 7 times in a row yields values I would expect:
val >>= 1 == 1100011110101000111011
val >>= 1 == 110001111010100011101
val >>= 1 == 11000111101010001110
val >>= 1 == 1100011110101000111
val >>= 1 == 110001111010100011
val >>= 1 == 11000111101010001
val >>= 1 == 1100011110101000
Why does val >> 3 not yield the same result as 3 calls to val >>= 1?
UPDATE:
My fault for using a decimal to binary converter on the web that was truncating my decimal input to 7 digits. When copy + pasting decimal values from Visual Studio, I didn’t notice the truncation occurring.
The actual value being shifted is 654245426 and as everyone is correctly pointing out, C# is bit-shifting this value perfectly.
I wrote code to output each shift:
and this is what I would expect to and did see.