【问题标题】:Converting a number in javascript to a 4 byte array将javascript中的数字转换为4字节数组
【发布时间】:2013-07-01 00:21:47
【问题描述】:

我正在尝试编写一个节点服务器,我需要在其中向 c# 客户端发送一个 32 位整数(作为标头)。

我不太确定该怎么做,因为位移运算符让我很困惑。我认为我的 c# 客户端期望这些整数采用小端格式(我不确定,我这么说是因为 NetworkStream IsLittleEndian 属性为真)。

假设我在 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);

如何编写 ConvertNumberTo4Bytes() 函数?

奖金

如何将这 2 个字节数组合并为一个,以便在一个 socket.write 调用中发送它们

【问题讨论】:

标签: c# javascript node.js network-programming


【解决方案1】:

感谢 elclanrs 的评论,在节点中使用 Buffer 对象似乎是可行的方法。

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

socket.write(buf);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2011-09-16
    • 2011-04-16
    • 2019-11-19
    • 1970-01-01
    相关资源
    最近更新 更多