Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manipulate bits 52-32 in Javascript, without strings?

I have the following, working prototype code:

function int2str(int, bits) {
    const str = int.toString(2);
    var ret = '';
    for (var i = 0; i < (bits - str.length); ++i) {
        ret += '0';
    }
    ret += str;
    return ret;
}

function high32(u64) {
    return parseInt(int2str(u64, 64).substr(0, 32), 2);
}

function low32(u64) {
    return parseInt(int2str(u64, 64).substr(32, 32), 2);
}

function combine(low, high) {
    return parseInt(int2str(high, 32) + int2str(low, 32), 2);
}

Can I do this more efficiently, without strings?

(Bitwise operators in Javascript cast to a 32-bit integer, making them useless.)

like image 568
fadedbee Avatar asked Feb 10 '26 16:02

fadedbee


1 Answers

Just ignores sign and lets the sign pass through. Uses division and convert to 32-bit integer to get high bits, and modulus for low bits.

const POW2_32 = (1<<16)*(1<<16)

function high32(u64) {
    return (u64/POW2_32)|0
}

function low32(u64) {
    return u64%POW2_32
}

function combine(low, high) {
    return high * POW2_32 + low
}

In case you want to accept signed numbers:

function high32(u64) {
    return (u64/((1<<16)*(1<<16)))
}

function low32(u64) {
    return Math.abs(u64%((1<<16)*(1<<16)))
}

function combine(low, high) {    
    return (high<0?-1:1) * // if high32 is neg, whole number is neg
           (Math.abs(high * POW2_32) + Math.abs(low|((low<0)<<15)))
                                       // if low bit is neg, set highest low bit
}

Also if you need to capture more than 32 bits for the high bits Math.trunc, and you will of course need to change everything to use BigInt (so 1n<<16n instead of 1<<16)

like image 103
user120242 Avatar answered Feb 13 '26 05:02

user120242



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!