Home > javascript, nodejs > [nodejs] working with big integers

[nodejs] working with big integers

Python
Under Python it’s very easy to work with big integers (called ‘long’ type in Python 2). The programmer doesn’t have to worry about the overflow error, the interpreter takes care of it. For instance, let’s calculate 2128:

>>> 2 ** 128
340282366920938463463374607431768211456

NodeJS
In JavaScript there is just a ‘number’ type, which is floating point. Actually, there is no integer type in JS :) And big integers are not supported, so you need a library if you want to work with huge numbers.

There is a very nice package called big-integer. It has an excellent documentation with lots of examples. Its usage is quite simple, similar to Java:

#!/usr/bin/env node

"use strict";

var bigInt = require("big-integer");

/*
 * 2 ** 128 == 340282366920938463463374607431768211456
 */

function main() {
    console.log(bigInt(2).pow(128).toString());
}

main();
Advertisements
Categories: javascript, nodejs Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: