将javascript中的数字转换为4字节的数组
我正在写一个节点服务器,我需要发送一个32位整数到ac#客户端(作为标题)。
我不太确定如何做到这一点,因为位移操作员混淆了我。 我认为我的C#客户端期望这些整数以小端格式(我不知道,我说,因为NetworkStream
IsLittleEndian属性是真的)。
所以说,我有一个JavaScript的variables是这样的
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);
如何编写ConvertNumberTo4Bytes()函数?
奖金
如何将这两个字节数组合并成一个,这样我就可以在一个socket.write调用中发送它们
在节点中使用Buffer
对象似乎是感谢elclanrs评论的方法。
var buf = new Buffer(4 + sizeOfPacket); buf.writeInt32LE(sizeOfPacket, 0); buf.write(packetToDeliverInBytes, 4); socket.write(buf);