我希望看到二进制形式的正整数或负整数。
很像这个问题,但是是针对JavaScript的。
我希望看到二进制形式的正整数或负整数。
很像这个问题,但是是针对JavaScript的。
当前回答
对于32位来说,我想要的解决方案是这个答案末尾的代码,它来自developer.mozilla.org(MDN),但是添加了一些行,用于A)格式化和B)检查数字是否在范围内。
有些人建议使用x.toString(2),这对负号不起作用,它只是在负号中插入负号,这是不好的。
Fernando提到了一个简单的解决方案(x>>>0).toString(2);对于负数来说没问题,但是当x是正数时就有点问题了。它的输出从1开始,对于正数来说不是2s的补码。
任何不理解正数以0开始和负数以1开始的事实的人,在2s补中,可以在2s补中检查这个SO QnA。什么是“2的补”?
一个解决方案可能包括在正数前面加上一个0,这是我在这个答案的早期修订中所做的。我们有时可以接受一个33位的数字,或者我们可以确保要转换的数字在-(2^31)<=x<2^31-1的范围内。所以这个数字总是32位的。但是,您可以在mozilla.org上使用这个解决方案
Patrick的回答和代码很长,显然适用于64位,但有一个bug,评论者发现了,评论者修复了Patrick的bug,但Patrick在他的代码中有一些“神奇的数字”,他没有评论,已经忘记了,Patrick不再完全理解他自己的代码/为什么它可以工作。
安南有一些不正确和不清楚的术语,但提到了developer.mozilla.org的解决方案
注意-旧链接https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators现在重定向到其他地方,没有内容,但适当的旧链接,当archive.org检索页面时出现!,可在此下载https://web.archive.org/web/20150315015832/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
这里的解决方案适用于32位数字。
代码非常紧凑,只有三行函数。
但是我添加了一个正则表达式,以8位为一组格式化输出。基于如何用逗号作为千位分隔符格式化一个数字?(我只是修改了一下,从右到左按3秒分组,加逗号,到右到左按8秒分组,加空格)
并且,虽然mozilla对nMask的大小(输入的数字)做了一个评论..它必须在范围内,当数字超出范围时,他们没有测试或抛出错误,所以我添加了这个。
我不知道为什么他们将参数命名为“nMask”,但我将保持原样。
https://web.archive.org/web/20150315015832/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
function createBinaryString(nMask) { // nMask must be between -2147483648 and 2147483647 if (nMask > 2**31-1) throw "number too large. number shouldn't be > 2**31-1"; //added if (nMask < -1*(2**31)) throw "number too far negative, number shouldn't be < -(2**31)" //added for (var nFlag = 0, nShifted = nMask, sMask = ''; nFlag < 32; nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1); sMask=sMask.replace(/\B(?=(.{8})+(?!.))/g, " ") // added return sMask; } console.log(createBinaryString(-1)) // "11111111 11111111 11111111 11111111" console.log(createBinaryString(1024)) // "00000000 00000000 00000100 00000000" console.log(createBinaryString(-2)) // "11111111 11111111 11111111 11111110" console.log(createBinaryString(-1024)) // "11111111 11111111 11111100 00000000" //added further console.log example console.log(createBinaryString(2**31 -1)) //"01111111 11111111 11111111 11111111"
其他回答
“convert to binary”中的二进制可以指三个主要的东西。位置数系统,内存中的二进制表示或32位位串。(64位位串参见Patrick Roberts的回答)
1. 数字系统
(123456). tostring(2)将数字转换为以2为基数的位置数字系统。在这个系统中,负数被写成负号,就像在十进制中一样。
2. 内部表示
数字的内部表示是64位浮点数,在这个答案中讨论了一些限制。没有简单的方法在javascript中创建一个比特字符串表示,也不能访问特定的位。
3.掩码和位操作符
MDN很好地概述了位操作符的工作方式。重要的是:
位操作符将其操作数视为32位序列(0和1)。
在应用操作之前,64位浮点数被转换为32位有符号整数。在它们被转换回来之后。
下面是将数字转换为32位字符串的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"
这就是解。事实上,这很简单
function binaries(num1){
var str = num1.toString(2)
return(console.log('The binary form of ' + num1 + ' is: ' + str))
}
binaries(3
)
/*
According to MDN, Number.prototype.toString() overrides
Object.prototype.toString() with the useful distinction that you can
pass in a single integer argument. This argument is an optional radix,
numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to
get a string representation of the binary for the base 10 number 100,
i.e. 1100100.
*/
我用了一种不同的方法来解决这个问题。我决定在我的项目中不使用这段代码,但我想我会把它放在相关的地方,以防它对某人有用。
Doesn't use bit-shifting or two's complement coercion. You choose the number of bits that comes out (it checks for valid values of '8', '16', '32', but I suppose you could change that) You choose whether to treat it as a signed or unsigned integer. It will check for range issues given the combination of signed/unsigned and number of bits, though you'll want to improve the error handling. It also has the "reverse" version of the function which converts the bits back to the int. You'll need that since there's probably nothing else that will interpret this output :D
function intToBitString(input, size, unsigned) { if ([8, 16, 32].indexOf(size) == -1) { throw "invalid params"; } var min = unsigned ? 0 : - (2 ** size / 2); var limit = unsigned ? 2 ** size : 2 ** size / 2; if (!Number.isInteger(input) || input < min || input >= limit) { throw "out of range or not an int"; } if (!unsigned) { input += limit; } var binary = input.toString(2).replace(/^-/, ''); return binary.padStart(size, '0'); } function bitStringToInt(input, size, unsigned) { if ([8, 16, 32].indexOf(size) == -1) { throw "invalid params"; } input = parseInt(input, 2); if (!unsigned) { input -= 2 ** size / 2; } return input; } // EXAMPLES var res; console.log("(uint8)10"); res = intToBitString(10, 8, true); console.log("intToBitString(res, 8, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, true)); console.log("---"); console.log("(uint8)127"); res = intToBitString(127, 8, true); console.log("intToBitString(res, 8, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, true)); console.log("---"); console.log("(int8)127"); res = intToBitString(127, 8, false); console.log("intToBitString(res, 8, false)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, false)); console.log("---"); console.log("(int8)-128"); res = intToBitString(-128, 8, false); console.log("intToBitString(res, 8, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, true)); console.log("---"); console.log("(uint16)5000"); res = intToBitString(5000, 16, true); console.log("intToBitString(res, 16, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 16, true)); console.log("---"); console.log("(uint32)5000"); res = intToBitString(5000, 32, true); console.log("intToBitString(res, 32, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 32, true)); console.log("---");
您可以编写自己的函数来返回一个比特数组。 示例如何将数字转换为比特
除数|被除数|位/余数
2 | | 1
2 4 | | 0
2 | 2 | 0
~ | | ~ 1
上面一行的例子:2 * 4 = 8,余数为1 9 = 1 0 0 1
function numToBit(num){
var number = num
var result = []
while(number >= 1 ){
result.unshift(Math.floor(number%2))
number = number/2
}
return result
}
从下往上读余数。数字1从中间到上面。
你可以使用递归解决方案:
函数intToBinary(number, res = "") { If (number < 1) If (res === "")返回"0" 其他的 返回res 否则返回intToBinary(数学。楼层(数目/ 2),数目% 2 + res) } console.log (intToBinary (12)) console.log (intToBinary (546)) console.log (intToBinary (0)) console.log (intToBinary (125)) 只对正数有效。