Javascript 是否有“0b”或类似的东西来表示Javascript中的二进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2803145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:00:10  来源:igfitidea点击:

Is there "0b" or something similar to represent a binary number in Javascript

javascript

提问by Misha Moroshko

I know that 0xis a prefix for hexadecimal numbers in Javascript. For example, 0xFFstands for the number 255.

我知道这0x是 Javascript 中十六进制数的前缀。例如,0xFF代表数字 255。

Is there something similar for binary numbers ? I would expect 0b1111to represent the number 15, but this doesn't work for me.

二进制数有类似的东西吗?我希望0b1111代表 number 15,但这对我不起作用。

回答by LukeH

Update:

更新:

Newer versions of JavaScript -- specifically ECMAScript 6 -- have added support for binary (prefix 0b), octal (prefix 0o) and hexadecimal (prefix: 0x) numeric literals:

较新版本的 JavaScript——特别是 ECMAScript 6——增加了对二进制(前缀0b)、八进制(前缀0o)和十六进制(前缀0x:)数字文字的支持:

var bin = 0b1111;    // bin will be set to 15
var oct = 0o17;      // oct will be set to 15
var oxx = 017;       // oxx will be set to 15
var hex = 0xF;       // hex will be set to 15
// note: bB oO xX are all valid

This feature is already available in Firefox and Chrome. It's not currently supported in IE, but apparently will be when Spartan arrives.

此功能已在 Firefox 和 Chrome 中可用。它目前在 IE 中不受支持,但显然在 Spartan 到来时会支持。

(Thanks to Semicolon's comment and urish's answerfor pointing this out.)

(感谢分号的评论和urish的回答指出了这一点。)

Original Answer:

原答案:

No, there isn't an equivalent for binary numbers. JavaScript only supports numeric literals in decimal (no prefix), hexadecimal (prefix 0x) and octal (prefix 0) formats.

不,二进制数没有等价物。JavaScript 仅支持十进制(无前缀)、十六进制(前缀0x)和八进制(前缀0)格式的数字文字。

One possible alternative is to pass a binary string to the parseIntmethod along with the radix:

一种可能的替代方法是将二进制字符串parseInt与基数一起传递给方法:

var foo = parseInt('1111', 2);    // foo will be set to 15

回答by urish

In ECMASCript 6 this will be supported as a part of the language, i.e. 0b1111 === 15is true. You can also use an uppercase B (e.g. 0B1111).

在 ECMASCRipt 6 中,这将作为语言的一部分得到支持,即为0b1111 === 15真。您也可以使用大写的 B(例如0B1111)。

Look for NumericLiteralsin the ES6 Spec.

NumericLiteralsES6 规范中查找。

回答by Juan Garcia

I know that people says that extending the prototypes is not a good idea, but been your script...

我知道人们说扩展原型不是一个好主意,而是你的脚本......

I do it this way:

我这样做:

Object.defineProperty(Number.prototype, 'b', {set:function(){return false;},get:function(){return parseInt(this, 2);}});

100..b       // returns 4
11111111..b  // returns 511
10..b+1      // returns 3

// and so on

回答by Pops

If your primary concern is display rather than coding, there's a built-in conversion system you can use:

如果您主要关心的是显示而不是编码,则可以使用内置的转换系统:

var num = 255;
document.writeln(num.toString(16)); // Outputs: "ff"
document.writeln(num.toString(8)); // Outputs: "377"
document.writeln(num.toString(2)); // Outputs: "11111111"

Ref: JavaScript Number Reference

参考:JavaScript 编号参考

回答by frodeborli

As far as I know it is not possible to use a binary denoter in Javascript. I have three solutions for you, all of which have their issues. I think alternative 3 is the most "good looking" for readability, and it is possibly much faster than the rest - except for it's initial run time cost. The problem is it only supports values up to 255.

据我所知,不可能在 Javascript 中使用二进制表示。我为您提供了三个解决方案,所有解决方案都有其问题。我认为替代方案 3 是最“好看”的可读性,它可能比其他方案快得多——除了它的初始运行时间成本。问题是它只支持最多 255 的值。

Alternative 1: "00001111".b()

备选方案 1: "00001111".b()

String.prototype.b = function() { return parseInt(this,2); }

Alternative 2: b("00001111")

备选方案 2: b("00001111")

function b(i) { if(typeof i=='string') return parseInt(i,2); throw "Expects string"; }

Alternative 3: b00001111

备选方案 3: b00001111

This version allows you to type either 8 digit binary b00000000, 4 digit b0000and variable digits b0. That is b01is illegal, you have to use b0001or b1.

此版本允许您输入 8 位二进制b00000000、4 位b0000和可变数字b0。那是b01非法的,你必须使用b0001or b1

String.prototype.lpad = function(padString, length) {
    var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}
for(var i = 0; i < 256; i++)
    window['b' + i.toString(2)] = window['b' + i.toString(2).lpad('0', 8)] = window['b' + i.toString(2).lpad('0', 4)] = i;

回答by Sergey Metlov

May be this will usefull:

可能这会很有用:

var bin = 1111;
var dec = parseInt(bin, 2);
// 15

回答by user1213898

No, but you can use parseInt and optionally omit the quotes.

不,但您可以使用 parseInt 并可选择省略引号。

parseInt(110, 2); // this is 6 
parseInt("110", 2); // this is also 6

The only disadvantage of omitting the quotes is that, for very large numbers, you will overflow faster:

省略引号的唯一缺点是,对于非常大的数字,溢出速度会更快:

parseInt(10000000000000000000000, 2); // this gives 1
parseInt("10000000000000000000000", 2); // this gives 4194304

回答by jpillora

Convert binary strings to numbers and visa-versa.

将二进制字符串转换为数字,反之亦然。

var b = function(n) {
    if(typeof n === 'string')
        return parseInt(n, 2);
    else if (typeof n === 'number')
        return n.toString(2);
    throw "unknown input";
};

回答by epeleg

I know this does not actually answer the asked Q (which was already answered several times) as is, however I suggest that you (or others interested in this subject) consider the fact that the most readable & backwards/future/cross browser-compatible way would be to just use the hex representation.

我知道这实际上并没有按原样回答所问的 Q(已经回答了好几次),但是我建议您(或其他对此主题感兴趣的人)考虑这样一个事实,即最具可读性和向后/未来/跨浏览器兼容方法是只使用十六进制表示。

From the phrasing of the Q it would seem that you are only talking about using binary literals in your code and not processing of binary representations of numeric values (for which parstInt is the way to go).

从 Q 的措辞来看,您似乎只是在谈论在代码中使用二进制文字,而不是处理数值的二进制表示(对于 parstInt 是要走的路)。

I doubt that there are many programmers that need to handle binary numbers that are not familiar with the mapping of 0-F to 0000-1111. so basically make groups of four and use hex notation.

我怀疑有很多需要处理二进制数的程序员不熟悉 0-F 到 0000-1111 的映射。所以基本上以四人为一组并使用十六进制表示法。

so instead of writing 101000000010 you would use 0xA02 which has exactly the same meaning and is far more readable and less less likely to have errors.

因此,不是写 101000000010,而是使用 0xA02,它的含义完全相同,可读性更强,出错的可能性更小。

Just consider readability, Try comparing which of those is bigger:
10001000000010010 or 1001000000010010

只考虑可读性,尝试比较哪个更大:
10001000000010010 或 1001000000010010

and what if I write them like this:
0x11012 or 0x9012

如果我这样写会怎样:
0x11012 或 0x9012

回答by Imagine Breaker

// Conversion function
function bin(nb)
{
    return parseInt(nb.toString(2));
}

// Test
var stop = false;
while(!stop)
{
    var n = parseInt(prompt("Type a decimal number : "));
    alert(bin(n));

    var str = prompt("Retry ? Y / N");
    if(str === "N") { stop = true; }
}