在JavaScript中将大整数转换为十六进制字符串 [英] Convert A Large Integer To a Hex String In Javascript

查看:179
本文介绍了在JavaScript中将大整数转换为十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一种在javascript中将大数字转换为十六进制字符串的方法。直接蝙蝠,我试过 myBigNumber.toString(16)但是如果 myBigNumber 有一个非常大的值(例如1298925419114529174706173 ),那么 myBigNumber.toString(16)将返回一个错误的结果,这真是太棒了。我试图用自己的函数写如下:

I need to find a way to convert a large number into a hex string in javascript. Straight off the bat, I tried myBigNumber.toString(16) but if myBigNumber has a very large value (eg 1298925419114529174706173) then myBigNumber.toString(16) will return an erroneous result, which is just brilliant. I tried writing by own function as follows:

function (integer) {
    var result = '';

    while (integer) {
        result = (integer % 16).toString(16) + result;
        integer = Math.floor(integer / 16);
    }
}

然而,大数模16都返回0(I我认为这个基本问题是导致 toString 问题的原因。我也试着用(integer%16)替换(integer - 16 * Math.floor(integer / 16))但是有同样的问题。

However, large numbers modulo 16 all return 0 (I think this fundamental issue is what is causing the problem with toString. I also tried replacing (integer % 16) with (integer - 16 * Math.floor(integer/16)) but that had the same issue.

也看了一下Big Integer Javascript库,但这是一个很大的插件,希望是相对直接的问题。

I have also looked at the Big Integer Javascript library but that is a huge plugin for one, hopefully relatively straightforward problem.

有关如何获得有效结果的任何想法?也许一些分而治之的方法?我真的很想在这里停下来。

Any thoughts as to how I can get a valid result? Maybe some sort of divide and conquer approach? I am really rather stuck here.

推荐答案

有问题的数字在javascript的最大整数之上。但是,你可以使用字符串来处理这么大的数字,并且有一些插件可以帮助你做到这一点。在这种情况下一个特别有用的例子是 hex2dec

The numbers in question are above javascript's largest integer. However, you can work with such large numbers by strings and there are some plugins which can help you do this. An example which is particularly useful in this circumstance is hex2dec

这篇关于在JavaScript中将大整数转换为十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆