Cryptography Reference
In-Depth Information
Listing 3-11:
“huge.c” set_huge
void set_huge( huge *h, unsigned int val )
{
unsigned int mask, i, shift;
h->size = 4;
// Figure out the minimum amount of space this “val” will take
// up in chars (leave at least one byte, though, if “val” is 0).
for ( mask = 0xFF000000; mask > 0x000000FF; mask >>=8 )
{
if ( val & mask )
{
break;
}
h->size--;
}
h->rep = ( unsigned char * ) malloc( h->size );
// Now work backward through the int, masking off each 8-bit
// byte (up to the first 0 byte) and copy it into the “huge”
// array in big-endian format.
mask = 0x000000FF;
shift = 0;
for ( i = h->size; i; i-- )
{
h->rep[ i - 1 ] = ( val & mask ) >> shift;
mask <<= 8;
shift += 8;
}
}
Notice that at the top of the
multiply
routine you see
set_huge( &temp, 0 );
but then you overwrite it immediately with a call to
copy_huge
. This is necessary
because the huge
temp
is allocated on the stack and is initialized with garbage
values. Because
copy_huge
immediately tries to free any pointer allocated, you
need to ensure that it's initialized to NULL.
set_huge
accomplishes this.
Start multiplying by setting aside a temporary space for the left-shifted fi rst
operand, copy that into the temporary space, and reset
h1
to 0. Then, loop
through each
char
of
h2
(backward, again), and check each bit of each
char
. If
the bit is a 1, add the contents of
temp
to
h1
. If the bit is a zero, do nothing. In
either case, left-shift
temp
by one position. Left-shifting a
huge
is, of course, a
separate operation that works on one
char
at a time, right-to-left.
Search WWH ::
Custom Search