Extract integer from tcp stream

I am using node.js to build a tcp server and I want to extract integers from the received data.

var net = require('net');
var server = net.createServer(function (socket) {
  socket.setEncoding('ascii');
  socket.addListener("data", function (data) {
    var pkgDataContent = data.substr(0, 2);
  });
});
server.listen(1337, "192.168.80.91");

The received data is a string type, and the numbers are 1 byte, 2 bytes and 4 bytes. How to extract these 1 byte, 2 byte and 4 byte integers from a javascript string? Like the code above: pkgDataContent is a string of 2 bytes, but it is actually an integer, how to convert it to javascript correctly?

+3
source share
2 answers

Depends on the essence and on whether it is signed or not.

32-bit unsigned integer:

pkgDataContent.charCodeAt(0) << (8*3) +
pkgDataContent.charCodeAt(1) << (8*2) +
pkgDataContent.charCodeAt(2) << (8*1) +
pkgDataContent.charCodeAt(3) << (8*0)

small final 32-bit unsigned integer:

pkgDataContent.charCodeAt(3) << (8*0) +
pkgDataContent.charCodeAt(2) << (8*1) +
pkgDataContent.charCodeAt(1) << (8*2) +
pkgDataContent.charCodeAt(0) << (8*3)
+4
source

"", , - Buffer. . , c, ,

typedef struct _SOME_PACKET
{
    unsigned short nLen; //2byte
    char szSomeMSg [16];    
} SOME_PACKET;

2 - . Buffer.

var littleEndianInt = data.readUInt16LE(0); 
//or
var bigEndianInt    = data.readUInt16BE(0);

2 , .

var restOfDataExceptInt = new Buffer( data.length - 2 ); 
restOfDataExceptInt.fill();
data.copy( restOfDataExceptInt, 0, 2, data.length  );

endian ? , endian .

[- ]

  • Linux x86, x64, Alpha Itanium
  • Mac OS X x86, x64
  • OpenVMS VAX, Alpha Itanium
  • Solaris x86, x64, PowerPC
  • Tru64 UNIX Alpha
  • Windows x86, x64 Itanium

[ ]

  • AIX on POWER
  • AmigaOS PowerPC 680x0
  • HP-UX Itanium PA-RISC
  • Linux MIPS, SPARC, PA-RISC, POWER, PowerPC, 680x0, ESA/390 /
  • Mac OS PowerPC 680x0
  • Mac OS X PowerPC
  • MVS DOS/VSE ESA/390 z/VSE z/OS z/Architecture
  • Solaris SPARC

:

https://github.com/jeremyko/nodeChatServer

.

+3

All Articles