Cryptography Reference
In-Depth Information
// Still overflowed; allocate more space
expand( h1 );
}
}
This routine adds the value of h2 to h1 , storing the result in h1 . It does so
in three stages. First, allocate enough space in h1 to hold the result (assuming
that the result will be about as big as h2 ). Second, the addition operation itself
is actually carried out. Finally, overfl ow is accounted for.
Listing 3-3: “huge.c” add routine (size computation)
if ( h2->size > h1->size )
{
unsigned char *tmp = h1->rep;
h1->rep = ( unsigned char * ) calloc( h2->size,
sizeof( unsigned char ) );
memcpy( h1->rep + ( h2->size - h1->size ), tmp, h1->size );
h1->size = h2->size;
free( tmp );
}
If h1 is already as long as or longer than h2 , in listing 3-3, nothing needs to
be done. Otherwise, allocate enough space for the result in h1 , and carefully
copy the contents of h1 into the right position. Remember that the char s are
read right-to-left, so if you allocate two new chars to hold the result, those
char s need to be allocated at the beginning of the array, so the old contents
need to be copied. Note the use of calloc here to ensure that the memory
is cleared.
If h1 is three char s and h2 is fi ve, you see something like Figure 3-1.
h1->rep
x
x
x
tmp
h1->rep
00x
x
x
Figure 3-1: Large Integer alignment
Note that if h2 is smaller than h1 , h1 is not changed at all, which means
that h1 and h2 do not necessarily line up, that is, you can add a three- char
number to a fi ve- char number — so you have to be careful to account for this
when implementing. This is the next step in the addition operation, shown
in Listing 3-4.
 
Search WWH ::




Custom Search