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'

2
  • 1
    possible duplicate of How to convert decimal to hex in JavaScript? Commented Mar 27, 2012 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. Commented Mar 27, 2012 at 12:19

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

@forste There. I'd recommend the second one.
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 oh yeah didn't see that tag. At least we've got answers for both then. :-)
1

For node.js bigdecimal.js works pretty well.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.