1

I'm taking my shot at writing a node server in which I need to send a 32 bit integer to a c# client (as the header).

I'm not quite sure how to do that, as the bit shift operators confuse me. I think my c# client expects these integers in little endian format (I'm not sure, I say that because the NetworkStream IsLittleEndian property is true).

So say I have a variable in javascript that's something like

var packetToDeliverInBytes = GetByteArrayOfSomeData();

//get the integer we need to turn into 4 bytes
var sizeOfPacket = packetToDeliver.length;

//this is what I don't know how to do
var bytes = ConvertNumberTo4Bytes(sizeOfPacket)

//then somehow do an operation that combines these two byte arrays together
//(bytes and packetToDeliverInBytes in this example)
//so the resulting byte array would be (packetToLiver.length + 4) bytes in size

//then send the bytes away to the client
socket.write(myByteArray);

How do I write the ConvertNumberTo4Bytes() function?

Bonus

How do I combine these 2 byte arrays into one so I can send them in one socket.write call

1

1 Answer 1

1

Using the Buffer object in node seems to be the way to go thanks to elclanrs comment.

var buf = new Buffer(4 + sizeOfPacket);
buf.writeInt32LE(sizeOfPacket, 0);
buf.write(packetToDeliverInBytes, 4);

socket.write(buf);
Sign up to request clarification or add additional context in comments.

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.