开发者

x-y = x+¬y+1 problem

I am currently reading a book abou开发者_JS百科t "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.)


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.


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.) .


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜