Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Significance of x & (-x) in 2's Complement?

Where '-' denotes negative x, and '&' denotes bitwise AND.

The numbers are in 8-bit 2's complement in a program and I can't seem to find the correlation between inputs and outputs.

8  & (-8)  = 8
7  & (-7)  = 1
97 & (-97) = 1

So possibly the significance is in the bit manipulation?

0000 1000 & (1111 1000) = 0000 1000
0000 0111 & (1111 1001) = 0000 0001
0110 0001 & (1001 1111) = 0000 0001

In each of the above cases the upper 4-bits always end up being 0's, but I cannot find a correlation between the inputs and what the lower 4-bits end up being.

Any ideas?

ANSWERED: Find the lowest set bit

like image 505
ThoseKind Avatar asked Oct 02 '17 18:10

ThoseKind


1 Answers

To expound on the other answer, the two's complement is equal to the one's complement of a number plus 1. Let's look at how adding 1 to the one's complement of 8 goes.

8 -> 00001000 (bin) -> 11110111 (oc) -> 11111000 (tc)

Here, notice how the added 1 moves through the one's complement until it reaches the first 0, flipping that bit and the bits to the right of it. And, also note that the position of the first 0 in the one's complement is also the position of the first 1 in the original binary expression.

In x & (-x), the bits to the left of the first 1 in x will be 0 because they are all still flipped from taking the one's complement. Then, the bits to the right of the first 1 will also be 0 because they were 0 in x (else the first 1 would be earlier).

Thus, the output of x & (-x) will be the power of 2 corresponding to the location of the first 1 in x.

like image 147
Jared Goguen Avatar answered Sep 30 '22 02:09

Jared Goguen