Re-interpret integer floating-point number

This question is probably "unusual", but I need to give the float to an Numberinteger Numberwithout changing its binary representation.

For example, a float 37.5is represented by bytes 0x42160000(according to IEEE 754). I need to rethink 0x42160000as an integer, i.e. Number1108738048

How should I do it? I think there might be some bitwise tricks for this?

To be clear, I'm not looking for Math.roundeither parseInt.

+5
source share
2 answers

: http://jsfiddle.net/rtYrM/.

// create array which is specialized for holding 1 float value
var floatArray = new Float32Array(1);

// set the float value
floatArray[0] = 37.5;

// use its buffer (4 bytes for 1 float) and pass it to an array
// specialized for integers
var intArray = new Int32Array(floatArray.buffer);

// the integer array will interpret the buffer bytes as an integer,
// which seems to be just what you want
intArray[0] === 1108738048; //true

intArray.buffer , floatArray.buffer, , , , , : Int32Array, float Float32Array.

( 10):

  • floatArray [ 37.5 ].
  • floatArray.buffer [ 0, 0, 22, 66 ].
  • floatArray.buffer , intArray.
  • intArray.buffer [ 0, 0, 22, 66 ].
  • intArray [ 1108738048 ], .
+5

, Javascript . Java java.lang.Float.floatBitsToIntBits(), . , , , , . , Javascript- , 100% .

0

All Articles