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

后端 未结 10 1262
太阳男子
太阳男子 2020-11-29 02:32

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

Is there something similar f

10条回答
  •  无人及你
    2020-11-29 03:11

    Update:

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

    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.

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

    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.

    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
    

提交回复
热议问题