I understand that in order to do a subtraction you should do a 2’s complement transformation to the second number .
Is there a dedicated Hardware for that checks the MSB and if it is found to be 1 it does the transformation ?
Also , Is this system used for subtraction of floating points ?
The Two’s Complement operation is implemented in most languages with the unary
-operator. It is only used with signed integer types. It can be implemented in an ALU as either a distinct negation (e.g.NEG) instruction or rolled into another operation, for example when you use a subtract (e.g.SUB) instruction instead of an add (e.g.ADD) instruction.Your first question is unclear because “the last bit” could refer to either the most-significant bit (MSB) or least significant bit (LSB). In a signed integer, the MSB indicates sign; checking for a negative is usually implemented as the
Nbit in the condition code register, which is updated from the result of the last instruction executed (though several instructions do not change the condition code register). Computing the two’s complement only if the original number is negative is the absolute value (e.g.ABS) operation. Checking the LSB just tells you if the integer is even or odd.Floating point numbers use a separate sign bit, so
0and-0are distinct values. Two’s compliment does not work with floating point values; a different approach must be used.EDIT: An example. Consider the following C code:
This can be run with:
On x86_64, the function
do_math()contains the following code:The first two lines are the preamble, setting up the stack for the function. The next four lines fetch the input parameters from the stack (since optimization was disabled, parameters weren’t passed in registers).
Then the key instruction:
subl, which takes the second parameter (%eax, the x86’s Extended AX register, 32 bits in size) and subtracts it from the first parameter (%edx, the x86’s Extended DX register, also 32 bits in size), storing the result back into%edx. In the ALU, thesublinstruction takes the first parameter as-is and adds the two’s complement of the second parameter. It calculates the two’s complement by inverting the second parameter’s bits (similar to the~operator in C) and then using a dedicated adder to add 1. This step could be pipelines, it could be optimized so both it and the final addition complete in one cycle, or they could go a step further and roll the two’s complement logic into the ALU’s adder chain.The last two lines clean up the stack and return. (The x86 calling conventions store the result in
%edx.EDIT 2: Use the
-Soption togccto generate an assembly file (same name as input file except.csuffix is replaced with.s). For example:gcc -O0 foo.c -S(Had I not turned off the optimizer with-O0, the entiredo_math()function could have been inlined intomain(), making it much harder to see.)