Cryptography Reference
In-Depth Information
OPERATION
REQUESTED
X SIGN
Y SIGN
ABS( X ) >
ABS( Y )?
MAGNITUDE
SIGN
add
+
Y
+
y
x
add
Y
y + x
subtract
+
+
N
+
x
y
subtract
+
N
x + y
+
subtract
+
N
x + y
subtract
N
x
y
subtract
+
+
Y
y
x
subtract
+
Y
y + x
+
subtract
+
Y
y + x
subtract
Y
y
x
+
To summarize, when adding or subtracting, if x is greater than y , invert the
operation if the signs of the operators are different. Perform the operation as
requested if the signs are the same. If x is less than y , swap the operators fi rst.
Of course, x y is the same as y x . This gives the magnitude. The sign of the
operation can be determined, essentially independently, as the following: If x is
greater than y , the result has the same sign as x , whether adding or subtracting.
Otherwise, if adding, and the operators have the same sign, the result has the
same sign as x ; if they differ, the result has the same sign as y . When subtracting,
and x is less than y , the sum has the opposite sign as x if x and y have the same
sign, and the opposite sign as y if x and y have different signs. You may fi nd it
worthwhile to work through a few examples to convince yourself that we've
covered every case, except for the exceptional case where x y , which is dealt
with specially because 0 is neither positive nor negative.
Follow these steps to support arbitrary-sized negative number addition and
subtraction.
1. Add an element to the huge struct from Listing 3-1 to keep track of its sign,
as shown in Listing 3-29. Let 0 represent positive and 1 represent negative:
Listing 3-29: “huge.h” huge structure with negative number support
typedef struct
{
int sign;
unsigned int size;
unsigned char *rep;
}
huge;
 
Search WWH ::




Custom Search