How to apply bitwise operations to the actual IEEE 754 representation of JS Numbers?

前端 未结 1 342
北恋
北恋 2021-01-23 12:18

In JavaScript, whenever you perform a bitwise operation such as x << 2, the 64-bit float representation gets converted to a 32-bit unsigned int before the shi

相关标签:
1条回答
  • 2021-01-23 12:49

    You might try converting the JSNumber to bytes/integers first and shifting the result yourself.

    Using TypedArray stuff available in recent versions of major browsers:

    var f = new Float64Array( 1 );    // creating typed array to contain single 64-bit IEEE754
    f.set( [ 1.0 ], 0 );              // transferring JSNumber for untyped array to first element of typed one
    var d = new DataView( f.buffer ); // creating raw view on content in typed array
    var w1 = d.getUint32( 0 );        // accessing bytes 0 to 3 of typed array
    var w2 = d.getUint32( 4 );        // accessing bytes 4 to 7 of typed array
    

    After that you could shift the 32-bit-words in w1 and w2 individually transferring upper 2 bits in lower word to lower 2 bits of upper word yourself.

    Endianess might be controlled on using second argument to d.getUint32().

    Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

    Just to ensure, comment of Bergi is recognized properly. All my code might be reduced to single line like that:

    var d = new Uint32Array( new Float64Array( [1.0] ).buffer );
    

    d[0] and d[1] are suitable for accessing contained 32-bit words, then.

    0 讨论(0)
提交回复
热议问题