简体   繁体   中英

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'

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

For node.js bigdecimal.js works pretty well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM