简体   繁体   English

将长十六进制编码从java移植到javascript

[英]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相同的方式编码javascript数字类型或字符串。

java java的

long toEncode = 1397378335821717182L;

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

javascript 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' https://stackoverflow.com/a/57805/1052539我得到'13647c315b7adf00'

You'll probably need a javascript bignum library. 你可能需要一个javascript bignum库。

This one seems to do what you want: http://www-cs-students.stanford.edu/~tjw/jsbn/ 这个似乎做你想做的事: 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: 看看有一个好看的(请参阅https://stackoverflow.com/questions/744099/javascript-bigdecimal-library ),但使用另一个谷歌点击 ,一些简单的示例代码是:

<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. 对于node.js来说bigdecimal.js工作得很好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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