Reputation: 143
I'm practicing hexadecimal subtraction and I seem to be stuck on this problem:
0B - 74
Could someone please explain how to perform this calculation? The hex answer is -69 but I can't seem to understand why. Should I try to convert to binary or a base 10 number to help me solve this?
Upvotes: 0
Views: 1768
Reputation: 71526
0x0B - 0x74 = 0x0B + (-0x74) as we know from grade school.
twos complement tells us that
-0x74 = (~0x74) + 1.
so a cpu solves it this way:
1
00001011
+ 10001011
============
finish filling it in, just like grade school but easier as it is base 2.
000010111
00001011
+ 10001011
============
10010111
the carry in and carry out of the msbit match so the answer fits. 0x97 which is -(0x68+1) = -0x69.
Also note if this had been 0x00B - 0x074 it still works
1
000000001011
+ 111110001011
===============
the result is 0xF97 which is -0x069. the beauty of twos complement.
(to negate a number in twos complement one way to do it is invert (ones complement) and add one)
you do not have to convert bases at all you can do base 16 math just as easily as base 10 or 2. If we want to subtract numbers from grade school we have to take the largest from the smaller
74
- 0B
======
b is larger than 4 so we have to borrow
1
64
- 0B
======
9
0x14 - b = 0x9.
1
64
- 0B
======
69
0x6 - 0x0 = 0x6.
because we had to flip the numbers because 0x74 is greater than 0x0b then we negate the result -0x69.
No magic. elementary math.
Upvotes: 2
Reputation: 16596
0x0B - 0x74 = 11 - 116 = -105 (-0x69)
In decimal 11-116 the second value is larger, so I do in my head instead -(116-11) flipping the values = -(105) = -105.
In hexa you can do the same -(0x74 - 0x0B), now for first (least significant) digit 0x4 - 0xB is again too much, so borrow one => 0x14-0x0B (20-11) = 9 (one digit found). Now second digits: 0x7 - 0x0 - borrow = 0x7 - 0x1 = 0x6 => full value 0x69 and the sign flipping is awaiting for this result = -0x69
And to verify result:
-0x69 + 0x74 = 0x0B (notice -0x9 + 0x4 is actually 0xB (11), because you go from 4 by 9 "down", i.e. 3, 2, 1, 0 (-4 done) and next is F (!), E, D, C, B (another -5 = -9 in total). It may be a bit difficult to keep the "base 16" on mind all the time, if you are used to decimal.
Upvotes: 1