Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read/Write bytes of float in JS

Tags:

Is there any way I can read bytes of a float value in JS? What I need is to write a raw FLOAT or DOUBLE value into some binary format I need to make, so is there any way to get a byte-by-byte IEEE 754 representation? And same question for writing of course.

like image 943
Michael Pliskin Avatar asked Dec 10 '10 23:12

Michael Pliskin


People also ask

How many bytes is a float in JavaScript?

There are also separate data types that you can use to store numbers with fractional part — 'float' which takes up 4 bytes and 'double' with 8 bytes.

Can we convert float to byte?

Float to Byte Array Conversion As we know, the size of a float in Java is 32 bit which is similar to an int. So we can use floatToIntBits or floatToRawIntBits functions available in the Float class of Java. And then shift the bits to return a byte array.

What is a byte in JavaScript?

The byte() function in p5. js is used to convert the given string of number, number value or boolean into its byte representation. This byte number can only be whole number in between -128 to 127. The value outside of the range is converted into its corresponding byte representation.


1 Answers

You can do it with typed arrays:

var buffer = new ArrayBuffer(4); var intView = new Int32Array(buffer); var floatView = new Float32Array(buffer);  floatView[0] = Math.PI console.log(intView[0].toString(2)); //bits of the 32 bit float 

Or another way:

var view = new DataView(new ArrayBuffer(4)); view.setFloat32(0, Math.PI); console.log(view.getInt32(0).toString(2)); //bits of the 32 bit float 

Not sure what browser support is like though

like image 72
Eric Avatar answered Sep 28 '22 08:09

Eric