views:

196

answers:

5

I am currently reading a book about "bit fiddling" and the following formula appears:

x-y = x+¬y+1

But this doesn't seem to work. Example:

x = 0100  
y = 0010  
x-y = 0010  
¬y = 1101  
¬y+1 = 1110  
x+1110 = 10010  

But 10010 != 0010...

Where did I make a mistake (if any)?

(The book is "Hacker's Delight" by Henry S. Warren.)

+2  A: 

You are carrying the extra bit. In real computers if you overflow the word, the bit disappears. (actually it gets saved in a carry flag.) .

deinst
+20  A: 

You only have a four bit system! That extra 1 on the left of your final result can't exist. It should be:

x  = 0100
y  = 0010
~y = 1101
~y + 1 = 1110
x + 1110 = 0010

The other bit overflows, and isn't part of your result. You may want to read up on two's complement arithmetic.

Carl Norum
Thank you very much :) Good explanation. Thanks to all others as well.
0x90
+2  A: 

Assuming the numbers are constrained to 4 bits, then the fifth 1 would be truncated, leaving you with 0010.

Adam Robinson
+1  A: 

It's all about overflow. You only have four bits, so it's not 10010, but 0010.

Alex Zylman
+1  A: 

Just to add to the answers, in a 2's complement system:

~x + 1 = -x

Say x = 2. In 4 bits, that's 0010.

~x = 1101
~x + 1 = 1110

And 1110 is -2

Aillyn