Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "faked subtraction" ever used in the real world?

Tags:

c

I'm taking a Computer Systems class as a pre-req for my Masters and came across something I found fascinating and hard to see practical use of and that is "faking subtraction" and the fact that there doesn't need to be a subtraction instruction.

Something like:

x - y

Can be written as:

x + (~y + 1)

Now, that's all well and good but it seems like that is overly complicated for a simple subtraction, especially when you could just easily put "x - y". Are there situations where it would be necessary to do this, or is it just something that CAN be done but isn't.

like image 871
Jetti Avatar asked Jun 16 '11 15:06

Jetti


2 Answers

This is often how it's done at the hardware level (i.e. inside the ALU).

At the software level, it's generally useless, as it can never be more efficient than the straightfoward subtraction (unless you have a truly bizarre compiler/platform combination).

like image 187
Oliver Charlesworth Avatar answered Oct 05 '22 23:10

Oliver Charlesworth


The two's complement implementation is done in hardware, so you do not need to implement them like that for builtin datatypes.

If you are making an n-bit integer arithmetic library, then you need to emulate the integer addition, subtraction, multiplication and division etc operations, in which case such a technique might be implemented to add the n-bit length numbers, but using the carry flag to do so is a better implementation in my opinion.

like image 29
phoxis Avatar answered Oct 06 '22 00:10

phoxis