Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between subtracting `x` and adding `-x` on an x86 machine?

Are there any semantics differences? Is one of them likely to be faster under specific circumstances?

like image 926
sanjoyd Avatar asked Jan 19 '13 16:01

sanjoyd


People also ask

How does a CPU do subtraction?

If it is a subtract operation you invert the second operand and put a one on the carry in and feed it to the same adder. Whatever falls out falls out. If your logic has enough bits to hold the result then it all works, if you do not have enough room then you overflow.

How is subtraction implemented using addition?

Well, we can subtract by adding. First, we just need to replace each digit of the smaller number with 9 minus that digit, except the final digit gets replaced with 10 minus that digit. So 1066 becomes 9 minus 1, 9 minus 0, 9 minus 6, 10 minus 6. Adding that to 1492 gives 10,426.

What is subtraction in computing?

Alternatively referred to as subtraction, subtract is a math operation that takes the value of one number from another number. An example of addition is 10 - 4 = 6. On a computer, you can subtract numbers using a calculator or spreadsheet program and the hyphen (-) or subtraction symbol.


1 Answers

If you have -x precomputed, then sub smth, x and add smth, -x are going to execute equally quickly.

Semantically, there will be a difference in terms of the flags state.

Consider doing 8-bit addition and subtraction:

0x01 - 0x01 = 0x00, CF = 0
0x01 + 0xFF = 0x00, CF = 1
like image 96
Alexey Frunze Avatar answered Oct 11 '22 13:10

Alexey Frunze