JS大数演算
4415 ワード
/**
*
*/
global.andorOpera = function (a, b, type) {
//type = 1 ,type = 2 ,
a = a + "";
b = b + "";
var aStr = toBin(a);
var bStr = toBin(b);
var longer = aStr.length > bStr.length ? aStr : bStr;
var sorter = aStr.length > bStr.length ? bStr : aStr;
var _tstr = "",
_fix = longer.length - sorter.length;
for (var i = longer.length - 1; i >= 0; i--) {
if (type == 2) {
//
_tstr += longer[i] == 1 || sorter[i - _fix] == 1 ? 1 : 0;
} else {
//
_tstr += longer[i] == 1 && sorter[i - _fix] == 1 ? 1 : 0;
}
}
// return parseInt(_tstr.split("").reverse().join(""),2);
return tobigInt(_tstr.split("").reverse().join(""));
}
//
function toBin(str) {
var arr = [];
var remainder, i, str2, num, char;
while (str.length > 0) {
str2 = "";
remainder = 0;
for (i = 0; i < str.length; i++) { // str2 = str / 2
num = str.charCodeAt(i) - 0x30; // num to String
num = remainder * 10 + num;
char = Math.floor(num / 2).toString();
// 0 , 0 str2
if (!(char === "0" && str2 === "")) {
str2 += char;
}
remainder = num % 2;
}
str = str2;
arr.push(remainder); //
}
return arr.reverse().join('');
}
// BigNumber = require('big-number');
function tobigInt(str) {
str = str.split("");
var length = str.length;
var temp = "0";
for (var i = length - 1; i >= 0; i--) {
temp = BigNumber(temp).add(str[i] == "1" ? (BigNumber("2").pow(length - 1 - i).number.reverse().join("")) : 0).number.reverse().join("");
}
return temp;
}