Search code examples
javascriptc++node.jsbignum

how to get uint256_t upper and lower part in nodejs/javascript,


i have equivalent c++ but not sure how to implement this in javascript/nodejs.

c++:

template <unsigned int BITS>
enum { WIDTH = BITS / 32 };
uint32_t pn[WIDTH];

    uint256 seed = "00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595d";

    
    uint64_t Get64(int n = 0) const
        {
            return pn[2 * n] | (uint64_t)pn[2 * n + 1] << 32;
        }
    
    uint64_t first = seed.Get64(0) % 6 + 1;
    uint64_t second = seed.Get64(1) % 6 + 1;

able to get uint64_t first with below. but not sure how to implement it for second one.

   //uint64_t first = seed.Get64(0) % 6 + 1;    
    
    var bigInt = require("big-integer");
        var hash = bigInt("00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595d",16);
        console.log(hash.and(new bigInt("ffffffffffffffff", 16)).mod(6) + 1)

//result of first = 6

Solution

  • How to do it with javascript "native" BigInt

    const get64 = (value, n=0) => (value >> BigInt(64*n)) & 0xffffffffffffffffn;
    const toNumber = value => +value.toString();
    
    var hash = 0x00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595dn;
    var first = toNumber(get64(hash, 0) % 6n + 1n);
    var second = toNumber(get64(hash, 1) % 6n + 1n);
    console.log(first, second)

    alternatively, you can do what many consider a big no-no and extend BigInt prototype - usually I'd suggest extending the BigInt class, but, that's not possible as far as I can tell (since new BigInt is not supported)

    BigInt.prototype.get64 = function (n=0) {
        return (this >> BigInt(64 * n)) & ((1n<<64n) - 1n);
    }
    BigInt.prototype.toNumber = function () {
        return +this.toString();
    }
        
    var hash = 0x00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595dn;
    var first = (hash.get64(0) % 6n + 1n).toNumber();
    var second = (hash.get64(1) % 6n + 1n).toNumber();
    console.log(first, second)