# 如何在JavaScript中将整数转换为二进制文件？

` `// IIFE to scope internal variables var float64ToInt64Binary = (function () { // create union var flt64 = new Float64Array(1) var uint16 = new Uint16Array(flt64.buffer) // 2**53-1 var MAX_SAFE = 9007199254740991 // 2**31 var MAX_INT32 = 2147483648 function uint16ToBinary() { var bin64 = '' // generate padded binary string a word at a time for (var word = 0; word < 4; word++) { bin64 = uint16[word].toString(2).padStart(16, 0) + bin64 } return bin64 } return function float64ToInt64Binary(number) { // NaN would pass through Math.abs(number) > MAX_SAFE if (!(Math.abs(number) <= MAX_SAFE)) { throw new RangeError('Absolute value must be less than 2**53') } var sign = number < 0 ? 1 : 0 // shortcut using other answer for sufficiently small range if (Math.abs(number) <= MAX_INT32) { return (number >>> 0).toString(2).padStart(64, sign) } // little endian byte ordering flt64[0] = number // subtract bias from exponent bits var exponent = ((uint16[3] & 0x7FF0) >> 4) - 1023 // encode implicit leading bit of mantissa uint16[3] |= 0x10 // clear exponent and sign bit uint16[3] &= 0x1F // check sign bit if (sign === 1) { // apply two's complement uint16[0] ^= 0xFFFF uint16[1] ^= 0xFFFF uint16[2] ^= 0xFFFF uint16[3] ^= 0xFFFF // propagate carry bit for (var word = 0; word < 3 && uint16[word] === 0xFFFF; word++) { // apply integer overflow uint16[word] = 0 } // complete increment uint16[word]++ } // only keep integer part of mantissa var bin64 = uint16ToBinary().substr(11, Math.max(exponent, 0)) // sign-extend binary string return bin64.padStart(64, sign) } })() console.log('8') console.log(float64ToInt64Binary(8)) console.log('-8') console.log(float64ToInt64Binary(-8)) console.log('2**33-1') console.log(float64ToInt64Binary(2**33-1)) console.log('-(2**33-1)') console.log(float64ToInt64Binary(-(2**33-1))) console.log('2**53-1') console.log(float64ToInt64Binary(2**53-1)) console.log('-(2**53-1)') console.log(float64ToInt64Binary(-(2**53-1))) console.log('2**52') console.log(float64ToInt64Binary(2**52)) console.log('-(2**52)') console.log(float64ToInt64Binary(-(2**52)))` `
` `.as-console-wrapper { max-height: 100% !important; }` `

` `function dec2bin(dec){ return (dec >>> 0).toString(2); } dec2bin(1); // 1 dec2bin(-1); // 11111111111111111111111111111111 dec2bin(256); // 100000000 dec2bin(-256); // 11111111111111111111111100000000` `

`-3 >>> 0` （右边的逻辑移位）强制它的参数为无符号整数，这就是为什么你得到32的二进制补码表示-3。

` `num.toString(2);` `

2是基数，可以是2到36之间的任何基数

` `function dec2Bin(dec) { if(dec >= 0) { return dec.toString(2); } else { /* Here you could represent the number in 2s compliment but this is not what JS uses as its not sure how many bits are in your number range. There are some suggestions https://stackoverflow.com/questions/10936600/javascript-decimal-to-binary-64-bit */ return (~dec).toString(2); } }` `

` `Number(42).toString(2); // "101010"` `

“转换为二进制”中的二进制可以指三个主要的东西。 位置数字系统，内存中的二进制表示或32位string。 （对于64位的位串，请参阅Patrick Roberts的答案 ）

1.数字系统

`(123456).toString(2)`将数字转换为基本2 位置数字系统 。 在这个系统中，负数用减号表示，就像十进制一样。

2.内部表示

3.掩码和按位运算符

MDN 很好地概述了按位运算符是如何工作的。 重要的：

` `function createBinaryString (nMask) { // nMask must be between -2147483648 and 2147483647 for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32; nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1); return sMask; } createBinaryString(0) //-> "00000000000000000000000000000000" createBinaryString(123) //-> "00000000000000000000000001111011" createBinaryString(-1) //-> "11111111111111111111111111111111" createBinaryString(-1123456) //-> "11111111111011101101101110000000" createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"` `

` `(-3>>>0).toString(2); prints -3 in 2s complement. 1111111111101` `

` `C:\>type n1.js console.log( (-3 >>> 0).toString(2) ); C:\> C:\>node n1.js 11111111111111111111111111111101 C:\>` `

` `javascript:alert((-3>>>0).toString(2))` `

` `// or x=-5 whatever number you want to view in binary x=5; if(x>0) prepend="0"; else prepend=""; alert(prepend+((x>>>0)).toString(2));` `

## 〜| 1 |〜

` `function numToBit(num){ var number = num var result = [] while(number >= 1 ){ result.unshift(Math.floor(number%2)) number = number/2 } return result }` `

` `var x = prompt("enter number", "7"); var i = 0; var binaryvar = " "; function add(n) { if (n == 0) { binaryvar = "0" + binaryvar; } else { binaryvar = "1" + binaryvar; } } function binary() { while (i < 1) { if (x == 1) { add(1); document.write(binaryvar); break; } else { if (x % 2 == 0) { x = x / 2; add(0); } else { x = (x - 1) / 2; add(1); } } } } binary();` `