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

查看:26
本文介绍了在 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(我认为这个基本问题是导致 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天全站免登陆