bit - why x>>1 is not always same as x/2? -


why x>>1 not same x/2?

especially when negative odd number, example:

    x = -3;     assert.assertnotequals(x / 2, x >> 1);     x =  3;     assert.assertequals(x / 2, x >> 1); 

thanks helps.

because of how >> works. >> not "divide 2", ends same answer situations. example, on 8-bit values:

3 0b00000011; right-shift 1 bit 0b00000001, 1.

-3 0b11111101; right-shift 1 bit 0b11111110, or -2.

however, integral division / in java defined round down towards 0 - (-3) / 2 becomes -1 (as closer 0 -2 is).

edit: comments refer brainfart in switching >> , >>> around.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -