Rez
Rez

Reputation: 187

Two's Complement Hex Subtraction

I'm looking at

0x0 - 0x21524111

in a two's comp system. I know the answer (DEADBEEF) but I'm uncertain about how to figure out these kinds of subtractions efficiently. Since I can't do carry-overs with 0x0, what should I do to get the result?

Upvotes: 0

Views: 1055

Answers (2)

OmegaNalphA
OmegaNalphA

Reputation: 710

Any subtraction in a two's complement system is really just an addition of the compliment. What you would need to do is take the inverse of 0x21524111 which becomes 0xDEADBEEF, then add it to 0x0 which is still 0xDEADBEEF.

Edit: Adding in that the 'inverse' means two's complement which means -a really is ~a + 1

Upvotes: 2

TallChuck
TallChuck

Reputation: 1972

The point of two's complement is to make subtraction easy by making it easy to get the negative of a number.

In general, if you have a number i, you can find -i by inverting all the bits of i and adding 1.

For example, if i = 0x21524111, then -i = ~0x21524111 + 1. Since a - b = a + (-b), you simply add -0x21524111 to 0.

a = 0
b = 0x21524111
c = ~b + 1
print a + c 
print a - b

Upvotes: 3

Related Questions