I am trying to implement Modular Exponentiation (square and multiply left to right) algorithm in c
.
In order to iterate the bits from left to right, I can use masking which is explained in this link
In this example mask used is 0x80
which can work only for a number with max 8 bits
.
In order to make it work for any number of bits, I need to assign mask dynamically but this makes it a bit complicated.
Is there any other solution by which it can be done.
Thanks in advance!
-------------EDIT-----------------------
long long base = 23;
long long exponent = 297;
long long mod = 327;
long long result = 1;
unsigned int mask;
for (mask = 0x80; mask != 0; mask >>= 1) {
result = (result * result) % mod; // Square
if (exponent & mask) {
result = (base * result) % mod; // Mul
}
}
As in this example, it will not work if I will use mask 0x80
but if I use 0x100
then it works fine.
Selecting the mask value at run time seems to be an overhead.