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
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.
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";
};
// 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; }
}
May be this will usefull:
var bin = 1111;
var dec = parseInt(bin, 2);
// 15
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
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