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

2

8

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

Cardioid answered 2/10, 2017 at 18:13 Comment(4)
Try a few more variations. You're almost there and I'm sure you'll be able to spot the pattern from a dozen examples.Kistler
Not near a computer, waiting to see the answer to this, can't solve it in my head! Flip bits and add 1 is what's happeningEndanger
It isolates the lowest set bit, and this has been answered before. Looking for a dupe..Mitzimitzie
@harold Found a version of the answer and edited the question. Thanks for the help.Cardioid
F
6

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.

Fuscous answered 2/10, 2017 at 18:36 Comment(0)
S
0

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.

Steapsin answered 2/10, 2017 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.