1

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 know what I'm doing wrong, but I get 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 readFloatLE: 3.60133705331478e-43

3
  • Documentation shows- const buf = Buffer.from([1,2,3,4,5,6,7,8]); buf.readDoubleBE(); // Returns: 8.20788039913184e-304 buf.readDoubleLE(); // Returns: 5.447603722011605e-270. But I don't know why. Curious myself. Commented Jun 2, 2016 at 21:30
  • Careful with new Buffer(size). That is deprecated with the most recent version of node. It might technically be okay, since you're overwriting the 4 bytes anyways, but I wanted to bring it up. Commented Jun 2, 2016 at 21:53
  • @MicahWilliamson side note: those are just the numbers represented. What you're making is a buffer containing 0x0102030405060708, and the doubles those represent are what you're seeing in your returns, based on whether you read them as big or little endian. Commented Jun 2, 2016 at 22:43

2 Answers 2

1

Here's a working set of data from front to back.

C#:

Single fl = 2.5F;
var bytes = System.BitConverter.GetBytes(fl);
var str = BitConverter.ToString(bytes); // 00-00-20-40

Nodejs:

let buffer = Buffer.from([ 0x00, 0x00, 0x20, 0x40 ]);
let float = buffer.readFloatLE(); // 2.5

Note the method I used to create the buffer in nodejs, especially (also tested and verified with -1, but I left the code off for brevity).

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks for the replies.

I put the same question over here:Unity Questions

Somebody give me the answer to use:

  readFloat: function (offset, data) {
        return data.readFloatLE(offset);

},

instead creating a new buffer.

Parameter is a buffer. This was working for me. I still don`t understand why my example is not working.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.