其中num 为整数,length为输出二进制位数
function intToBits(num, length) {
if(isNaN(num) || num === num+1)
return null;
if(typeof length !== "number" || isNaN(length) || length === length+1 || length < 1 || length === undefined)
length = 32;
var origNum = num;
var bits = [];
var importantBits = 1;
for(var i=0; i<32; i++) {
var curBit = num % 2 == 0 ? '0' : '1';
bits.unshift(curBit);
num = num >> 1;// 右移一位相当于除2,右移n位相当于除以2的n次方。
if(num !== 0)
importantBits++;
}
return bits.reverse().splice(0,Math.max(importantBits, length)).reverse().join('');
}