views:

46

answers:

1

Now, this is simple enough when the numbers are small, but numbers like "9223372036854775807" are too large for parseInt().

I'm not sure how to do this within the Google docs script editor, which doesn't seem to allow for external classes.

+1  A: 

Here you go, used this script somewhere and it seems to work. The idea behind it is that it splits the string to 8-character chunks, and calculates chunk/2, then sums the chunks up and gets a result of division by 2.

By dividing by 2 - it easily calculates the result then.

var maxIntSize = 8;

function divide2(number, addup, depth) {
    var result = "";

    var partLength = Math.min(number.length,maxIntSize); 
    var part = number.substring(0,partLength);

    var partNum = parseInt(part,10);
    var partAdd = (addup==0)?0:(5*Math.pow(10,partLength-1));
    var partRes = Math.floor(partNum/2)+partAdd;
    var partRem = partNum%2;

    result = result + partRes;

    if (depth > 0) {
        for (var i=result.length; i < partLength; i++) {
            result = "0"+result;
        }
    }

    var nextPart = number.substring(partLength, number.length);

    if (partLength < number.length) {
        var res = divide2(nextPart, partRem, depth+1);
        result = result + res.result;
        res.result = result;
        return res;
    } else {
        var res = {result: result, remainder: partRem};
        return res;
    }
}

function toBinary(number) {
    var out = "";

    while (number.length > 1 || number != "0") {
        var res = divide2(number,0,0);
        out = "" + res.remainder + out;
        number = res.result;
    }

    return out;
}

var testNum = "12312312312112312312312312312312312312312312312312312312312312312312312312312312312312312312123";
document.write("bin("+testNum+") = "+toBinary(""+testNum)+"<br/>");

Division to chunks is required to calculate division by 2 faster. This script works pretty fast even for huge numbers.

Max