问题描述
我在python中有一个工作脚本,根据指定的基数进行字符串到整数的转换,使用 long(16)
:
I have a working script in python doing string to integer conversion based on specified radix using long(16)
:
modulus=public_key["n"]
modulusDecoded = long(public_key["n"], 16)
它打印:
8079d7ae567dd2c02dadd1068843136314fa3893fa1fb1ab331682c6a85cad62b208d66c9974bbbb15d52676fd9907efb158c284e96f5c7a4914fd927b7326c40efa14922c68402d05ff53b0e4ccda90bbee5e6c473613e836e2c79da1072e366d0d50933327e77651b6984ddbac1fdecf1fd8fa17e0f0646af662a8065bd873
和
90218878289834622370514047239437874345637539049004160177768047103383444023879266805615186962965710608753937825108429415800005684101842952518531920633990402573136677611127418094912644368840442620417414685225340199872975797295511475162170060618806831021437109054760851445152320452665575790602072479287289305203
分别。
这看起来像十六进制到十进制转换。
我试图在JS中获得相同的结果,但 parseInt()
和 parseFloat()
完全生成一些东西不同。最重要的是,JavaScript似乎不喜欢输入字符串中的字符,有时会返回NaN。
respectively.This looks like a Hex to decimal conversion.I tried to have the same result in JS but parseInt()
and parseFloat()
produce something completely different. On top of that JavaScript seems not to like chars in input string and sometimes returns NaN.
任何人都可以提供函数/指导如何获得与Python相同的功能脚本?
Could anyone please provide a function / guidance how to get the same functionality as in Python script?
推荐答案
JavaScript中的数字是浮点数,因此它们在某个数字后总是会失去精度。要拥有无限数字,我们可以使用0到9之间的数字数组,它具有无限范围。要根据十六进制字符串输入执行此操作,我执行十六进制到int数组转换,然后使用将数组转换为BCD。这可以很容易打印出来:
Numbers in JavaScript are floating point so they always lose precision after a certain digit. To have unlimited numbers one could rather use an array of numbers from 0 to 9, which has an unlimited range. To do so based on the hex string input, i do a hex to int array conversion, then I use the double dabble algorithm to convert the array to BCD. That can be printed easily:
const hexToArray = arr => arr.split("").map(n => parseInt(n,16));
const doubleDabble = arr => {
var l = arr.length;
for( var b = l * 4; b--;){
//add && leftshift
const overflow = arr.reduceRight((carry,n,i) => {
//apply the >4 +3, then leftshift
var shifted = ((i < (arr.length - l ) && n>4)?n+3:n ) << 1;
//just take the right four bits and add the eventual carry value
arr[i] = (shifted & 0b1111) | carry;
//carry on
return shifted > 0b1111;
}, 0);
// we've exceeded the current array, lets extend it:
if(overflow) arr.unshift(overflow);
}
return arr.slice(0,-l);
};
const arr = hexToArray("8079d7");
const result = doubleDabble(arr);
console.log(result.join(""));
这篇关于Javascript - 将字符串解析为long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!