Tuesday, September 10, 2013

C++ Convert number to base 2

A method to convert a BigInt to base 2


int* Base2Conversion(BigInt num)
{    int totBits = num.bits();
    int *i = new int[totBits];
    int idx = 1;
 
    do{
        i[totBits - idx] = num%2;
        num /= 2;
        idx++;
    }
    while(num > 0);

return i;
}
 
 
 //Use of the method above
BigInt num = 453453463465767897809789787687456765476;
int totBits = num.bits();
int* binary = Base2Conversion(num); BigInt result = 1;
for(int i = 1; i < totBits; i++)
{
    result *= result;

    if(binary[i] == 1)
    {
        result *= 5;
    }
}
 
 

No comments: