Converting large numbers from binary to decimal and back in JavaScript

后端 未结 4 1930
感动是毒
感动是毒 2020-11-29 11:54

I have a very large number represented as binary in JavaScript:

 var largeNumber = \'110100110101101000010100111110100101110111110000100101110001111100111110         


        
4条回答
  •  盖世英雄少女心
    2020-11-29 12:10

    If you're looking to transfer a large amount of binary data, you should use BigInt. BigInt allows you to represent an arbitrary number of bits.

    // parse large number from string
    let numString = '1101001101011010000101001111101001011101111100001001'
    
    // as number
    let num = BigInt('0b' + numString)
    
    // now num holds large number equivalent to numString
    console.log(num)  // 3718141639515913n
    
    // print as base 2
    console.log(num.toString(2))  // 1101001101011010000101001111101001011101111100001001
    

    Helper functions

    // some helper functions
    
    // get kth bit from right
    function getKthBit(x, k){
      return (x & (1n << k)) >> k;
    }
    
    // set kth bit from right to 1
    function setKthBit(x, k){
      return (1n << k) | x;
    }
    
    // set kth bit from right to 0
    function unsetKthBit(x, k){
      return (x & ~(1n << k));
    }
    
    getKthBit(num, 0n);  
    // 1n
    
    getKthBit(num, 5n);  
    // 0n
    
    setKthBit(num, 1n).toString(2); 
    // 1101001101011010000101001111101001011101111100001011
    
    setKthBit(num, 4n); 
    // 1101001101011010000101001111101001011101111100011001
    
    unsetKthBit(num, 0n).toString(2);
    // 1101001101011010000101001111101001011101111100001000
    
    unsetKthBit(num, 0n).toString(2);
    // 1101001101011010000101001111101001011101111100000001
    

    For convenience you may want to add this to BigInt if you're going to be serializing back to the client. Then you can read it back as a string. Otherwise you will get "Uncaught TypeError: Do not know how to serialize a BigInt" because for some reason Javascript Object Notation doesn't know how to serialize one of the types in Javascript.

        Object.defineProperty(BigInt.prototype, "toJSON", {
            get() {
                "use strict";
                return () => this.toString() + 'n';
            }
        });
    

提交回复
热议问题