javascriptjquerybigintegerjsbn

jsbn.js BigInteger - how to instantiate with a normal number?


I tried both :

var a = new BigInteger(5);

And

var b = new BigInteger(5, 10);

But both give me the error:

TypeError: 'undefined' is not an object (evaluating 'b.nextBytes')
bnpFromNumberjsbn2.js:126

Can you only instantiate with strings?


Solution

  • I'd wanted to give a better answer, but you didn't mention WHICH BigInteger library you were using.

    // Yes, use the two '..'
    var a = new BigInteger(5..toString());
    
    // Of if you have a variable
    var v = 10;
    var a = new BigInteger(v.toString());
    

    now, with this knowledge you can override BigInteger

    (function() {
      var oldConstructor = BigInteger;
      BigInteger = function(v) {
        if (typeof v === "number") {
          return oldConstructor(""+v);
        }
        return oldConstructor(v);
      };
    
    }());