Javascript - parse string to long

前端 未结 3 353
南方客
南方客 2021-01-02 02:11

I have a working script in python doing string to integer conversion based on specified radix using long(16):

modulus=public_key[\"n\"]    
modu         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 03:00

    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(""));
    

    Try it

提交回复
热议问题