If you have a really large binary number (that exceeds the Number.MAX_SAFE_INTEGER
value), then you can store it as the BigInt
primitive data type.
For example, if you're using the ES6 binary number syntax, then you could do the following:
// ES6+ const largeBinNum = BigInt(0b11111111111111111111111111111111111111111111111111111); console.log(largeBinNum); // 9007199254740991n
Similarly, if you're using a binary string, then you could do the following:
const largeBinNum = BigInt('11111111111111111111111111111111111111111111111111111'); console.log(largeBinNum); // 9007199254740991n
Please note that the "n
" at the end of the result merely suggests that the resulting number is a bigint primitive. You can easily convert it to a string or a number.
Please note that a BigInt
value cannot be used with the Math
object methods and cannot be mixed with a Number
value in operations. For that, you must coerce the value into the same type. However, be aware that coercing values back and forth might mean that the precision of a BigInt
value may be lost when it is coerced to a Number
value.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.