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

后端 未结 10 1198
太阳男子
太阳男子 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 02:59

    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.

    0 讨论(0)
  • 2020-11-29 02:59

    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";
    };
    
    0 讨论(0)
  • 2020-11-29 03:02
    // 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; }
    }
    
    0 讨论(0)
  • 2020-11-29 03:04

    May be this will usefull:

    var bin = 1111;
    var dec = parseInt(bin, 2);
    // 15
    
    0 讨论(0)
  • 2020-11-29 03:06

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

    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
    
    0 讨论(0)
  • 2020-11-29 03:08

    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

    0 讨论(0)
提交回复
热议问题