简体   繁体   English

将javascript中的数字转换为4字节数组

[英]Converting a number in javascript to a 4 byte array

I'm taking my shot at writing a node server in which I need to send a 32 bit integer to ac# client (as the header). 我正在写一个节点服务器,在其中我需要向ac#客户端(作为标头)发送32位整数。

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). 我认为我的C#客户端希望这些整数采用小端序格式(我不确定,因为NetworkStream IsLittleEndian属性为true,所以我不能这么说)。

So say I have a variable in javascript that's something like 所以说我在javascript中有一个变量,就像

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? 如何编写ConvertNumberTo4Bytes()函数?

Bonus 奖金

How do I combine these 2 byte arrays into one so I can send them in one socket.write call 我如何将这两个字节数组组合为一个,以便可以在一个socket.write调用中发送它们

Using the Buffer object in node seems to be the way to go thanks to elclanrs comment. 感谢elclanrs的评论,在节点中使用Buffer对象似乎是一种方法。

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

socket.write(buf);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM