This question is probably “unusual”, but I need to cast a float Number to an integer Number, without modifying its binary representation.
For example, the float 37.5 is represented by the bytes 0x42160000 (according to IEEE 754).
I need to reinterpret 0x42160000 as an integer, i.e. the number 1108738048
How do I do this? I’m thinking there could be some bitwise tricks to accomplish this?
To be clear, I’m not looking for Math.round or parseInt.
Typed arrays can come in handy here: http://jsfiddle.net/rtYrM/.
intArray.bufferwill hold the same bytes asfloatArray.buffer, but by not accessing it with the buffer but with the array itself, it will read those bytes as the type specified by the typed array: as integers forInt32Array, and as floats forFloat32Array.In this case (in base 10):
floatArrayis set to the value[ 37.5 ].floatArray.bufferis automatically set to the values[ 0, 0, 22, 66 ].floatArray.bufferis passed to a new integer array,intArray.intArray.buffertherefore contains the values[ 0, 0, 22, 66 ]as well.intArraycontains the value[ 1108738048 ], calculated with its buffer.