Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Diff: BigInt.cpp
- Revision:
- 24:a3453a18388c
- Parent:
- 23:002f471a973e
- Child:
- 25:3d5c1f299da2
diff -r 002f471a973e -r a3453a18388c BigInt.cpp
--- a/BigInt.cpp Mon Mar 10 21:59:19 2014 +0000
+++ b/BigInt.cpp Sun Apr 06 08:12:52 2014 +0000
@@ -15,7 +15,12 @@
0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000
};
-static uint32_t num(const uint32_t a)
+static uint32_t BITS2[] =
+{
+ 0x00FFFFFF, 0x0000FFFF, 0x00FFFFFF
+};
+
+static inline uint32_t num(const uint32_t a)
{
return a/4 + (a%4 ? 1:0);
}
@@ -539,14 +544,14 @@
while(r > 0)
{
if(a.bits[j/32] & BITS[j%32])
- result += b;
+ result.add(b);
if(result.bits[0] & BITS[0])
- result += m;
+ result.add(m);
++j;
--r;
- result >>= 1;
+ result.shr();
}
if(result >= m)
@@ -579,6 +584,7 @@
uint32_t j = 0;
while(j <= n)
{
+
if(expn.bits[j/32] & BITS[j%32])
{
if(tmp.isValid())
@@ -589,6 +595,7 @@
++j;
if(j <= n)
montA = montgomeryStep(montA, montA, modulus, r);
+
}
// convert tmp to normal world
@@ -613,6 +620,50 @@
printf("\n");
}
+void BigInt::add(const BigInt &b)
+{
+ uint32_t al = num(size);
+ uint32_t bl = num(b.size);
+ uint32_t rsize = std::max(size, b.size) + 1;
+ size_t l = num(rsize);
+
+ if(l > al)
+ {
+ bits = (uint32_t*)realloc(bits, sizeof(uint32_t)*l);
+ memset(&bits[al], 0, (l-al)*sizeof(uint32_t));
+ size = rsize;
+ }
+
+ uint32_t carry = 0;
+ for(int i = 0; i < l; ++i)
+ {
+ uint32_t tmpA = 0, tmpB = 0;
+ if(i < al)
+ tmpA = bits[i];
+ if(i < bl)
+ tmpB = b.bits[i];
+ bits[i] = tmpA + tmpB + carry;
+ carry = bits[i] < std::max(tmpA, tmpB);
+ }
+
+ trim();
+}
+
+void BigInt::shr()
+{
+ uint32_t lastBit = 0;
+ uint32_t tmp;
+ for(int i = num(size)-1; i >= 0; --i)
+ {
+ tmp = bits[i] & BITS[0];
+ bits[i] >>= 1;
+ bits[i] |= (lastBit ? BITS[31] : 0);
+ lastBit = tmp;
+ }
+
+ trim();
+}
+
void BigInt::trim()
{
assert(isValid());
@@ -623,15 +674,12 @@
newSize--;
if(newSize == 0)
newSize = 1;
- if(num(newSize) < num(size))
+ uint32_t n = num(newSize);
+ if(n < num(size))
{
- uint32_t *tmp = new uint32_t[num(size)];
- memcpy(tmp, bits, num(size)*sizeof(uint32_t));
- delete[] bits;
- bits = new uint32_t[num(newSize)];
- memset(bits, 0, sizeof(uint32_t)*num(newSize));
- memcpy(bits, tmp, newSize);
- delete[] tmp;
+ bits = (uint32_t*)realloc(bits, n*sizeof(uint32_t));
+ if(newSize % 4 != 0)
+ bits[n-1] &= BITS2[newSize%4];
}
size = newSize;
}
@@ -651,4 +699,4 @@
n += tmp2;
return n;
-}
+}
\ No newline at end of file