javascript 大数值进行按位运算

// 将十进制转换为2进制  
function toBin(intNum) {
	  var answer = "";
	  if(/\d+/.test(intNum)) {
		while(intNum != 0) {
		  answer = Math.abs(intNum%2)+answer;
		  intNum = parseInt(intNum/2);
		}
		if(answer.length == 0)
		  answer = "0";
		return answer;
	  } else {
		return 0;
	  }
}

 // 返回num个0的字符串拼接
 function addZero (num)
 {
	 var result = '';
	 for ( i=0;i= 0;i--)
	   {
		   result = ((str1.charAt(i)=='1' && str2.charAt(i)=='1') ? '1' : '0') + result;
	   }
       return parseInt(result,2);
 }

// 大数值按位或
 function  bigIntOr(str1,str2)
 {
	   var result = '';
	   str1 = toBin(str1);
	   str2 = toBin(str2);
	   if(str1.length < str2.length)
	   {
             var temp = str1;
			 str1 = str2;
		     str2 = temp;
	   }
	   str2 = addZero(str1.length - str2.length) + str2;
	  

	   for (i = str2.length - 1 ;i >= 0;i--)
	   {
		  result = ((str1.charAt(i)=='1' || str2.charAt(i)=='1') ? '1' : '0') + result;
	   }
	   result = str1.substring (0,str1.length - str2.length) +result;
	   return parseInt(result,2);
 }

你可能感兴趣的:(javascript 大数值进行按位运算)