Cryptography Reference
In-Depth Information
else if ( h1->rep[ i ] > h2->rep[ j ] )
{
return 1;
}
i++;
j++;
}
Of course, if you go through both h1 and h2 , and they're both the same size,
and each char is equal, then they both represent equal numbers.
Referring to the original divide function, the second step is to allocate space
for the quotient by keeping track of how many times the dividend was left
shifted. The quotient can't be any bigger than this, which overallocates just a
bit, but not so much that you need to worry about it.
quotient->size = ( bit_size / 8 ) + 1;
quotient->rep = ( unsigned char * )
calloc( quotient->size, sizeof( unsigned char ) );
memset( quotient->rep, 0, quotient->size );
Finally, start the “compare and subtract” loop. If the current dividend, after
being left-shifted, is less than the current divisor, then the quotient should have
that bit position set, and the current dividend should be subtracted from the
divisor. In all cases, the dividend should be right-shifted by one position for
the next loop iteration. Although the comparison, subtraction and right-shift
operators are easy to understand — they just call the compare and subtract
functions coded earlier — the setting of the “current” bit of the quotient is
somewhat complex:
quotient->rep[ ( int ) ( bit_position / 8 ) ] |=
( 0x80 >> ( bit_position % 8 ) );
Remember that bit_position is absolute. If quotient is a 128-bit number,
bit_position ranges from 0 to 127. So, in order to set the correct bit, you need
to determine which char this refers to in the array of chars inside quotient and
then determine which bit inside that char you need to set (that is, or ). This may
look familiar; this is essentially the SET_BIT macro developed in Chapter 2.
Finally, right-shift the divisor at each step except the last:
if ( bit_size )
{
right_shift( divisor );
}
Technically, you could get away with always right-shifting and not skipping
this on the last step, but by doing this, you guarantee that divisor is reset to
the value that was passed in to the function originally. This is useful behavior
because you are calling “divide” over and over again with the same argument,
which keeps you from having to make a temporary copy of the divisor.
right_shift , the reverse of left_shift , is shown in Listing 3-15.
Search WWH ::




Custom Search