最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reinterpret cast floating point number to integer - Stack Overflow

programmeradmin3浏览0评论

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 acplish this?

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

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 acplish this?

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

Share Improve this question edited May 17, 2012 at 17:03 mskfisher 3,4124 gold badges37 silver badges49 bronze badges asked Sep 24, 2011 at 11:35 BartBart 27.3k1 gold badge25 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Typed arrays can e in handy here: http://jsfiddle/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 will hold the same bytes as floatArray.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 for Int32Array, and as floats for Float32Array.

In this case (in base 10):

  • floatArray is set to the value [ 37.5 ].
  • floatArray.buffer is automatically set to the values [ 0, 0, 22, 66 ].
  • floatArray.buffer is passed to a new integer array, intArray.
  • intArray.buffer therefore contains the values [ 0, 0, 22, 66 ] as well.
  • intArray contains the value [ 1108738048 ], calculated with its buffer.

I don't believe Javascript includes any mechanism for doing this. There's a method java.lang.Float.floatBitsToIntBits() in Java, so depending on your intended environment you might be able to make use of that. If all else fails, you might have to send the data back to the server to be converted. Alternatively, I've seen attempts at Javascript methods to do this conversion, but never one that was 100% plete and correct.

发布评论

评论列表(0)

  1. 暂无评论