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

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

Look for NumericLiterals in the ES6 Spec.


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

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

Tags:

Javascript