forste
forste

Reputation: 1133

porting long hex encoding from java to javascript

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'

Upvotes: 2

Views: 693

Answers (2)

forste
forste

Reputation: 1133

For node.js bigdecimal.js works pretty well.

BigDec> (new bigdecimal.BigInteger('1397378335821717182')).toString(16)
'13647c315b7adebe'

Upvotes: 1

wds
wds

Reputation: 32283

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

Upvotes: 2

Related Questions