2

I want to encode a javascript number-type or string in the same way I encode a Java long.

java

long toEncode = 1397378335821717182L;

String encoded = Long.toHexString(toEncode); //"13647c315b7adebe"

javascript

var toEncode = '1397378335821717182';

var encoded = //missing code, should be'13647c315b7adebe' in the end as well

doing https://stackoverflow.com/a/57805/1052539 I get '13647c315b7adf00'

Community
  • 1
  • 1
forste
  • 1,103
  • 3
  • 14
  • 33
  • 1
    possible duplicate of [How to convert decimal to hex in JavaScript?](http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript) – Quentin Mar 27 '12 at 12:13
  • 1
    @Quentin not a duplicate, his numbers don't fit in a double so doing it that way he'll lose precision. – wds Mar 27 '12 at 12:19

2 Answers2

2

You'll probably need a javascript bignum library.

This one seems to do what you want: http://www-cs-students.stanford.edu/~tjw/jsbn/

edit: The one I linked doesn't seem to work. Look around a bit for a nice one (see also https://stackoverflow.com/questions/744099/javascript-bigdecimal-library), but using another google hit, some simple example code is:

<script>
  var toEncode = str2bigInt('1397378335821717182', 10);
  document.write(bigInt2str(toEncode, 16).toLowerCase());
</script>

returns: 13647c315b7adebe

Or with this library (which is, at the very least, better scoped):

<script type="text/javascript" src="biginteger.js"></script>
<script>
  var toEncode = BigInteger.parse('1397378335821717182');
  document.write(toEncode.toString(16).toLowerCase());
</script>

returns: 13647c315b7adebe
Community
  • 1
  • 1
wds
  • 31,873
  • 11
  • 59
  • 84
  • @forste There. I'd recommend the second one. – wds Mar 27 '12 at 12:48
  • ty again for updating! however, I should have made it more obvious that I need this for node.js. I have put an own answer for this – forste Mar 28 '12 at 13:40
  • @forste oh yeah didn't see that tag. At least we've got answers for both then. :-) – wds Mar 28 '12 at 15:08
1

For node.js bigdecimal.js works pretty well.

BigDec> (new bigdecimal.BigInteger('1397378335821717182')).toString(16)
'13647c315b7adebe'
forste
  • 1,103
  • 3
  • 14
  • 33