Convert float to byte array and read with node js
Hello,
Can someone explain how I can convert a float(Vector3.x) to a byte array with c# and decode it with node js?
I read on the internet that Vector3.x is a system.single data type and use 4 bytes(32 bits). I use BitConverter to convert it to a byte array. With Nodejs I use readFloatBE().
I don`t what I do wrong, but I got constantly a bad result with node js with console.log().
Unity csharp:
public static int FloatToBit(int offset, ref byte[] data, Single number)
{
byte[] byteArray = System.BitConverter.GetBytes(number);
for (int i = 0;i<4;i++)
{
data[offset + i] = byteArray[i];
}
return 4;
}
Node js
readFloat: function (offset, data) {
var b = new Buffer(4);
for (var i = 0; i < 4; i++) {
b[i] = data[offset + i];
}
return data.readFloatLE(b, 0);
},
If I send -2.5, unity output is: 0 0 32 191 with -1 unity output is: 0 0 128 192
Nodejs output with read: 3.60133705331478e-43
Answer by Bunny83 · Jun 03, 2016 at 03:13 AM
I never really used the Buffer object to read / convert float values, but shouldn't you use:
return b.readFloatLE(0);
Just have a look at the documentation.
If "data" is a Buffer as well you should be able to just do this:
readFloat: function (offset, data) {
return data.readFloatLE(offset);
},
readFloatLE already does what your readFloat method should do.
Wow, it`s working. THAN$$anonymous$$S!!!!
I still don`t understand why b.readFloatLE is not working. data.readFloatLE is better and faster way. I gonna use that. Despite that, i am still curious why the other way is not working.
Your answer
![](https://koobas.hobune.stream/wayback/20220612082147im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
error CS1525: Unexpected symbol `float' 1 Answer
Timer float not evaluating correctly when I check if it's less than another number 3 Answers
Can I compare a Transform variable (x, y, z) against float variables? 1 Answer
float value is reset after every update 1 Answer
currentSpeed doesnt change when pressing Shift (C#) 1 Answer