如何在 JavaScript 中将整数转换为二进制?

2022-01-17 00:00:00 numbers javascript

我想查看整数,无论​​是正整数还是负整数.

I’d like to see integers, positive or negative, in binary.

比较喜欢这个问题,但对于 JavaScript.

Rather like this question, but for JavaScript.

推荐答案

我会采用的解决方案适用于 32 位,是这个答案结尾的代码,来自 developer.mozilla.org(MDN),但添加了一些行用于 A) 格式化和 B) 检查数字是否在范围内.

A solution i'd go with that's fine for 32-bits, is the code the end of this answer, which is from developer.mozilla.org(MDN), but with some lines added for A)formatting and B)checking that the number is in range.

一些建议的 x.toString(2) 不适用于负数,它只是在其中贴一个减号,这不好.

Some suggested x.toString(2) which doesn't work for negatives, it just sticks a minus sign in there for them, which is no good.

Fernando 提到了 (x>>>0).toString(2); 的简单解决方案,它适用于负数,但当 x 为正数时有一个小问题.它的输出以 1 开头,对于正数,它不是正确的 2s 补码.

Fernando mentioned a simple solution of (x>>>0).toString(2); which is fine for negatives, but has a slight issue when x is positive. It has the output starting with 1, which for positive numbers isn't proper 2s complement.

任何不了解以 0 开头的正数和以 1 开头的负数在 2s 补码中的事实的任何人都可以检查此 SO QnA on 2s 补码.什么是2的补码"?

Anybody that doesn't understand the fact of positive numbers starting with 0 and negative numbers with 1, in 2s complement, could check this SO QnA on 2s complement. What is "2's Complement"?

解决方案可能涉及为正数添加 0,这是我在此答案的早期版本中所做的.有时可以接受 33 位数字,或者可以确保要转换的数字在 -(2^31)<=x<2^31-1 范围内.所以这个数字总是32位.但是,您可以在 mozilla.org 上使用此解决方案,而不是这样做

A solution could involve prepending a 0 for positive numbers, which I did in an earlier revision of this answer. And one could accept sometimes having a 33bit number, or one could make sure that the number to convert is within range -(2^31)<=x<2^31-1. So the number is always 32bits. But rather than do that, you can go with this solution on mozilla.org

Patrick 的答案和代码很长,显然适用于 64 位,但有一个评论者发现的错误,评论者修复了 patrick 的错误,但 patrick 的代码中有一些他没有评论的神奇数字"关于并且已经忘记并且帕特里克不再完全理解他自己的代码/它为什么起作用.

Patrick's answer and code is long and apparently works for 64-bit, but had a bug that a commenter found, and the commenter fixed patrick's bug, but patrick has some "magic number" in his code that he didn't comment about and has forgotten about and patrick no longer fully understands his own code / why it works.

Annan 有一些不正确和不清楚的术语,但提到 developer.mozilla.org 的解决方案 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators 这适用于 32 位数字.

Annan had some incorrect and unclear terminology but mentioned a solution by developer.mozilla.org https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators This works for 32-bit numbers.

代码很紧凑,三行函数.

The code is pretty compact, a function of three lines.

但是我已经添加了一个正则表达式来格式化输出 8 位组.基于 如何打印数字逗号作为 JavaScript 中的千位分隔符(我只是将其修改为从右到左将其分组为 3s 并添加 commas,以分组为 8s 从右到左,并添加 空格)

But I have added a regex to format the output in groups of 8 bits. Based on How to print a number with commas as thousands separators in JavaScript (I just amended it from grouping it in 3s right to left and adding commas, to grouping in 8s right to left, and adding spaces)

而且,虽然 mozilla 对 nMask 的大小(输入的数字)发表了评论..它必须在范围内,但当数字超出范围时,他们没有测试或抛出错误,所以我已经添加了.

And, while mozilla made a comment about the size of nMask(the number fed in)..that it has to be in range, they didn't test for or throw an error when the number is out of range, so i've added that.

我不确定他们为什么将参数命名为nMask",但我会保持原样.

I'm not sure why they named their parameter 'nMask' but i'll leave that as is.

参考: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"

相关文章