ThoseKind
ThoseKind

Reputation: 804

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

Upvotes: 8

Views: 3168

Answers (2)

Jared Goguen
Jared Goguen

Reputation: 9008

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.

Upvotes: 6

Pac0
Pac0

Reputation: 23174

Two's complement is by definition, equals to the one's complement (all bits inversed) plus one.

If you were to do only the number & and its one complement, it would always give 0000 0000.

The key to understand the pattern lies here : if the + 1 operation changes other bits or only the last one. That is, if the number has a 1 at the end, and also if any reminder will propagate after the +1 addition.

Upvotes: 0

Related Questions