是否有“0b”或类似的东西代表Javascript中的二进制数 [英] Is there "0b" or something similar to represent a binary number in Javascript

查看:134
本文介绍了是否有“0b”或类似的东西代表Javascript中的二进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that 0x is a prefix for hexadecimal numbers in Javascript. For example, 0xFF stands for the number 255.

二进制数是否类似?我希望 0b1111 代表数字 15 ,但这对我不起作用。

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

推荐答案

更新:

新版本的JavaScript - 特别是ECMAScript 6 - 增加了对二进制(前缀 0b )和八进制(前缀 0o )数字文字的支持: / p>

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

var foo = 0b1111;    // foo will be set to 15
var bar = 0o17;      // bar will be set to 15

此功能已在Firefox和Chrome中提供。它目前在IE中不受支持,但显然是在Spartan到货时。

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

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

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

原始答案:

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

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.

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

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

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

这篇关于是否有“0b”或类似的东西代表Javascript中的二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆