2013-07-01 49 views
1

我正在寫一個節點服務器,我需要發送一個32位整數到一個c#客戶端(如標題)。將JavaScript中的數字轉換爲4字節的數組

我不太確定如何做到這一點,因爲位移操作員會混淆我。我認爲我的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()函數?

獎金

如何這兩個字節數組合併爲一個,這樣我可以在一個socket.write通話

+3

看看是否有幫助:http://nodejs.org/api/buffer.html#buffer_buf_readuint32le_offset_noassert – elclanrs

回答

1

送他們使用Buffer對象節點似乎是去感謝的方式向elclanrs發表評論。

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

socket.write(buf); 
相關問題