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

主宰稳场 提交于 2019-12-02 12:16:30

问题


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 shifting actually occurs. I am insterested in applying the shift to the actual, unaltered IEEE 754 bitwise representation.

How is that possible?


回答1:


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.



来源:https://stackoverflow.com/questions/24564460/how-to-apply-bitwise-operations-to-the-actual-ieee-754-representation-of-js-numb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!