I want to understand the semantics of rights bit shifts x>>k
in two's complement properly, in particular why do right bit shifts of size $k$ approximately divide $x$ by $2^k$ (and ideally making this "approx" precise and also handling the arithmetic left bit shift too).
So the representation of a number in two complement is for a $N$ bit length word:
$$
x = -a_{N-1} 2^{N-1} + \sum^{N-2}_{i=0} a_{i} 2^i = neg + pos
$$
e.g., as a intentionally selected running example $-6$ is $1010_2$ which is $-8 + 0 + 2 + 0$. I'm thinking of bit slots [-8, 4, 2, 1] <-> [-2^3, 2^2, 2^1, 2^0]
for each bit. When doing an arithmetic right bit shift we get $1101_2$ which ends up being $-3 = -8 + 4 + 0 + 1$ in twos complement.
When the most significant bit (MSB) is $0$ the mathematics seems trivial. If you move the bits to the right it's a division by two because every number is divided by two (maybe floor since we lose the final bit sometimes if it's 1). With negative numbers using 2s complement it seems more complicated. We want -6 -> -3
. Intuitively I would have assumed to "double" the positive part $pos$ but that doesn't quite work and results in left shift on $pos$ anyway. So no.
I've worked out a couple (many?) examples and wrote the equations but I can't seem to figure out the pattern. Why is a right bit arithmetic where you "carry the MSB" work with the intended semantics (divide by $2^k$ or multiply by $2^k$) for both positive and negative representations of numbers?
I've read related questions but I am still confused:
- Why does shifting right on a two's complement binary number divide it by 2?
- Why Two's Complement works
- https://stackoverflow.com/questions/44694957/the-difference-between-logical-shift-right-arithmetic-shift-right-and-rotate-r/78130029#78130029
- https://en.wikipedia.org/wiki/Two%27s_complement#:~:text=Two's%20complement%20is%20the%20most,number%20is%20positive%20or%20negative.
n >> k == ~((~n) >> k)
, where~n
is the complementation operator. In two's complement, we have~n == -1 - n
. So from this you can pretty much deduce the result for negative numbers straight away. Another way to think about two's complement is "binary strings that go infinitely far left, but are always eventually all ones or all zeroes". The $2$-adic metric is then a meaningful sense in which $\dots 111 = -1$. – Izaak van Dongen Mar 09 '24 at 01:07