snippetjavascriptTip
Convert between binary and decimal numbers in JavaScript
Viewed 0 times
javascriptdecimalbinaryandbetweenconvertnumbers
Problem
I don't often work with binary numbers, but whenever I do, I find myself looking up certain pieces of information over and over again. This is especially true when I need to convert a binary string to a decimal number or vice versa. Let's take a look at how to do this in JavaScript.
Given a binary string, you can use
You may also use the
> [!TIP]
>
Given a binary string, you can use
Number.parseInt() with a base of 2 to indicate the string is in binary format and convert it to its decimal equivalent.You may also use the
BigInt constructor to convert a binary string to a BigInt. This is useful when dealing with very large numbers that exceed the range of regular integers.> [!TIP]
>
Solution
const binaryToDecimal = binary => Number.parseInt(binary, 2);
binaryToDecimal('10'); // 2
binaryToDecimal('110'); // 6You may also use the
BigInt constructor to convert a binary string to a BigInt. This is useful when dealing with very large numbers that exceed the range of regular integers.> [!TIP]
>
> Notice the
0b prefix in the string passed to BigInt? This prefix indicates that the string is a binary number. In fact, you can use this in your code when writing out a numeric value in binary, like this:>
>
Code Snippets
const binaryToDecimal = binary => Number.parseInt(binary, 2);
binaryToDecimal('10'); // 2
binaryToDecimal('110'); // 6const binaryToBigInt = binary => BigInt(`0b${binary}`);
binaryToBigInt('10'); // 2n
binaryToBigInt('110'); // 6n> const binaryNumber = 0b10; // 2 (Number)
> const bigIntBinaryNumber = 0b10n; // 2n (BigInt)
>Context
From 30-seconds-of-code: binary-number-conversion
Revisions (0)
No revisions yet.