Cryptography Reference
In-Depth Information
Listing 3-31: “huge.c” add_magnitude and subtract_magnitude
/**
* Add two huges - overwrite h1 with the result.
*/
static void add _magnitude ( huge *h1, huge *h2 )
{
unsigned int i, j;
unsigned int sum;
unsigned int carry = 0;
...
/**
* Subtract h2 from h1, overwriting the value of h1.
*/
static void subtract _magnitude ( huge *h1, huge *h2 )
{
int i = h1->size;
int j = h2->size;
int difference; // signed int - important!
unsigned int borrow = 0;
...
if ( borrow && i )
{
if ( h1->rep[ i - 1 ] ) // Don't borrow i
{
// negative reults are now OK
h1->rep[ i - 1 ]--;
}
}
Nothing else changes in these routines.
4. Now, create two new routines named add and subtract that invoke add_
magnitude and subtract_magnitude , after performing the rules described
by Table 3-2 as shown in Listing 3-32. These new routines have the same
method signatures as the old add and subtract . In fact, they end up tak-
ing their places, which means you need to relink anything linked using
the old object fi le. This won't be a problem because your Make rules are
set up correctly.
Listing 3-32: “huge.c” add with negative number support
void add( huge *h1, huge *h2 )
{
int result_sign;
// First compute sign of result, then compute magnitude
if ( compare( h1, h2 ) > 0 )
(Continued)
Search WWH ::




Custom Search