从 TCP 流中提取整数
我正在使用node.js构建一个tcp服务器,我想从接收到的数据中提取整数。
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");
接收到的数据为字符串类型,数字为1字节、2字节、4字节。如何从 JavaScript 字符串中提取这些 1 字节、2 字节和 4 字节整数?就像上面的代码:pkgDataContent是一个2字节的字符串,但实际上它是一个整数,如何将它正确地转换为javascript数字?
I am using node.js to build a tcp server, and I want to extract integers from the data received.
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 data received is 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 actually it is an integer, how to convert it to javascript number correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
取决于字节顺序以及是否已签名。
大端 32 位无符号整数:
小端 32 位无符号整数:
Depends on endianness and on whether it's signed or not.
big endian 32-bit unsigned integer:
little endian 32-bit unsigned integer:
函数中传递的“数据”是 Buffer 对象。它可以包含任何二进制数据。
假设接收到的数据包是这样的普通c结构,
那么数据的前2个字节是二进制数据。可以通过Buffer的方法得到整数。
要获取2个字节后的剩余数据,可以使用offset。
使用哪种字节序?这取决于您的计算机使用哪种字节序。
[little-endian 系统]
[big-endian 系统]
PowerPC 上的z/Architecture
也请参阅此:
https://github.com/jeremyko/nodeChatServer
希望有所帮助。
The 'data' passed in your function is Buffer object. it can contain any binary data.
Suppose that a received packet is the plain c structure like this,
then the first 2 byte of data is binary data. and you can get the integer by Buffer's method.
To get the rest data after 2 bytes, you can use offset.
which endian to use? it depends on which endian your computer use.
[little-endian system]
[big-endian system]
z/Architecture
also please refer to this:
https://github.com/jeremyko/nodeChatServer
Hope this help.