A binary number is a numeral system with a base of 2, using only two symbols (0 and 1) to represent all values. In contrast, the decimal system, which is the most common numeral system used by people, has a base of 10 and uses ten symbols (0 through 9) to represent values.
Given a binary number:
In this number, represents the number of bits in the binary number, and the value of is either or for each digit. You can use the following equation to calculate decimal number manually:
For example, if you have the binary number :
dec = = = 13
You can also use the
let bin = 0b101010; console.log(bin); // 42 console.log(typeof bin); // "number"
A binary string is a string that consists of only
parseInt() function to convert a binary string to a decimal number, or the
toString() method to convert a decimal number to a binary string.
// Convert binary string to decimal number let bin = "101010"; let dec = parseInt(bin, 2); // Specify radix 2 for binary console.log(dec); // 42 // Convert decimal number to binary string let num = 42; let sbin = num.toString(2); // Specify radix 2 for binary console.log(sbin); // "101010"
The parseInt function takes a string as the first argument and a radix as the second argument, and returns an integer in decimal. The radix is the base of the number system that the string represents. For example, binary is base 2, decimal is base 10, hexadecimal is base 16, and so on.
You can’t use the
0b prefix in a binary string when using parseInt because the parseInt function does not recognize it as a valid radix prefix. The only prefix that parseInt recognizes is
0X for hexadecimal values. Everything else is parsed as a decimal value if the radix is missing. If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
let bin = "0b101010"; let dec = parseInt(bin, 2); // Specify radix 2 for binary console.log(dec); // 0
Number()constructor creates Number objects. When called as a function, it returns primitive values of type Number.
If you pass a binary number using
0b prefix to the Number constructor, it will return the same number as a decimal number.
let bin = 0b101010; // 0b101010 is 42 in decimal let dec = Number(bin); // No radix specified console.log(dec); // 42 console.log(typeof dec); // "number"
Also work with binary string using
let bin = "0b101010"; // 0b101010 is 42 in decimal let dec = Number(bin); console.log(dec); // 42 console.log(typeof dec); // "number"
0b prefix, binary string passed to Number constructor will be used as is decimal:
let bin = "101010"; let dec = Number(bin); console.log(dec); // 101010 console.log(typeof dec); // "number"