Question

I'm currently learning JavaScript and I'm very surprised there is not built-in way to work with binary numbers. I have to work with integers up to 2^4096 so I just can't use JS integers for my calculus.

My first thought was to use Arrays of 1 and 0. But that's not satisfying since a simple multiplication by 2 requires to shift the whole table.

So how can I work efficiently with binary numbers in JavaScript ?

I'd like not to use any library. I'm interested in how it works, not in using other's abstraction.

Was it helpful?

Solution

Javascript doesn't have any biginteger type, so you would need to use an array to hold that much information.

An array of 0 and 1 values would make it easy to implement functions for it, but not very efficient.

A regular number in Javascript is a double precision floating point number, so it can hold 52 bits of numeric information (ref), but you would use slightly less to be far away from any rounding errors, for example 48 bits.

The bitwise operators in Javascript work with 32 bit integers, i.e. a double is converted to a 32 bit integer when used with a bitwise operator. If you want to use the bitwise operators on the data, you could choose to store 32 bits per item in the array.

OTHER TIPS

JavaScript only supports 53 bit integers.

The best way to store "big integers" is to convert them to strings on server side. And in case you want to manipulate them I would suggest to look at this library https://github.com/rauschma/strint

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top