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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With