0

I'm trying to do operations in 160 bit integers using the bigInteger.js library, but I want to keep a representation of those in hex format so I can transmit them over and use them as ID.

var git_sha1 = require('git-sha1');
var bigInt = require("big-integer");

var uuid = git_sha1((~~(Math.random() * 1e9)).toString(36) + Date.now());
console.log('in hex \t', uuid); // See the uuid I have
console.log('in dec \t', bigInt(uuid, 16).toString()); // convert it to bigInt and then represent it as a string
console.log('to hex \t', bigInt(uuid, 16).toString(16)); // try to convert it back to hex

Here is my output:

in hex   4044654fce69424a651af2825b37124c25094658
in dec   366900685503779409298642816707647664013657589336
to hex   366900685503779409298642816707647664013657589336

I need that to hex to be the same as in hex. Any suggestions? Thank you!

David Dias
  • 1,792
  • 3
  • 16
  • 28
  • It seems that bigInt ignores the radix parameter :( https://github.com/peterolson/BigInteger.js/blob/master/BigInteger.js#L317-L331 meaning I will have to 'monkey patch it', any idea how to convert a string in dec to a string in hex? – David Dias Oct 08 '14 at 13:52
  • Not sure about numbers of that size but have you tried this: http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript – CompanyDroneFromSector7G Oct 08 '14 at 14:03

2 Answers2

2

This was fixed with the PR of https://github.com/peterolson/BigInteger.js/pull/18

David Dias
  • 1,792
  • 3
  • 16
  • 28
0

I don't know if you're that attached to big-integer, but if you're not, bigint does exactly what you want.

EDIT : If you want to keep big-integer, this should do the trick :

function toHexString(bigInt) {
  var output = '';
  var divmod;
  while(bigInt.notEquals(0)) {
    divmod = bigInt.divmod(16);
    bigInt = divmod.quotient;
    if (divmod.remainder >= 10)
      output = String.fromCharCode(87+divmod.remainder) + output;
    else
      output = divmod.remainder + output;
  }
  return output;
}
ploutch
  • 1,204
  • 10
  • 12