Javascript node.js中的二进制结构
我正在编写一个服务器,并通过TCP接收缓冲区。这是一个结构 因此,通常是这样做的:Javascript node.js中的二进制结构,javascript,c,node.js,Javascript,C,Node.js,我正在编写一个服务器,并通过TCP接收缓冲区。这是一个结构 因此,通常是这样做的: typedef struct _ref_{ uint8_t x; uint8_t *y; uint8_t z[16]; }REF; 与上面的代码无关,我的缓冲区可能看起来像: 01 00 00 00 0A 可定义为:(小endian) 那就是 1, 0, 10 x: 1, y: 0, z: 10 我想把它转换成json对象,比如 UINT16 is X, UINT16 is Y,
typedef struct _ref_{
uint8_t x;
uint8_t *y;
uint8_t z[16];
}REF;
与上面的代码无关,我的缓冲区可能看起来像:
01 00 00 00 0A
可定义为:(小endian)
那就是
1, 0, 10
x: 1, y: 0, z: 10
我想把它转换成json对象,比如
UINT16 is X, UINT16 is Y, UINT8 is Z
那么结果就是
1, 0, 10
x: 1, y: 0, z: 10
但是如何在node.js中实现(与浏览器无关)
我看到了,但它不支持以null结尾的字符串,这些字符串是特定于长度的 我还看到了最近出现的一些问题,但仍然存在以null结尾的字符串的问题。类似的问题
var buffer = your_input_data;
var result = {
x: buffer.readUInt16LE(0),
y: buffer.readUInt16LE(2),
z: buffer.readUInt8(4)
}
console.log(JSON.stringify(result));
像这样的
var buffer = your_input_data;
var result = {
x: buffer.readUInt16LE(0),
y: buffer.readUInt16LE(2),
z: buffer.readUInt8(4)
}
console.log(JSON.stringify(result));
在寻找合适的库之后,我决定编写自己的库来支持以null结尾的字符串 它被称为
c-struct
,您可以找到它
安装:
npm install c-struct --save
语法:
var playerSchema = new _.Schema({
id: _.type.uint16,
name: _.type.string(16),
hp: _.type.uint24,
exp: _.type.uint32,
status: _.type.uint8,
motd: _.type.string(), // null-terminated if no length
motw: _.type.string(), // cstring if no length
skills: [{
id: _.type.uint8,
name: _.type.string(32),
secret: _.type.uint40
}],
position: {
x: _.type.uint16,
y: _.type.uint16
},
hash: _.type.uint48
});
在寻找合适的库之后,我决定编写自己的库来支持以null结尾的字符串 它被称为
c-struct
,您可以找到它
安装:
npm install c-struct --save
语法:
var playerSchema = new _.Schema({
id: _.type.uint16,
name: _.type.string(16),
hp: _.type.uint24,
exp: _.type.uint32,
status: _.type.uint8,
motd: _.type.string(), // null-terminated if no length
motw: _.type.string(), // cstring if no length
skills: [{
id: _.type.uint8,
name: _.type.string(32),
secret: _.type.uint40
}],
position: {
x: _.type.uint16,
y: _.type.uint16
},
hash: _.type.uint48
});
您是在寻找一种通用解决方案,支持不同编码的有符号/无符号短/长整数/浮点数和以空结尾的字符串,还是只支持以特定字节数和ASCII字符串签名的简单解决方案?支持以小尾端顺序以特定字节数无符号的简单解决方案,也可以是ASCII字符串,不管是否以null结尾。什么是不以null结尾的字符串?那么如何检测字符串的结尾呢?是的,如果给定字符串的特定长度,它们都可以解析字符串。与缓冲区类似,缓冲区包含2个字符串,由null分隔。它们可以是任意长度的。但它们总是从到。因此,
到:'thistfirst string',从:'this the second string'
您是否在寻找一般解决方案,支持有符号/无符号短/长整数/浮点数和不同编码的空终止字符串,或仅支持特定字节数和ASCII字符串的简单字符串?支持特定字节数的无符号短/长整数/浮点数和空终止字符串的简单字符串,以小端序排列,也可以处理ASCII字符串,是否以null结尾。不以null结尾的字符串是什么意思?那么如何检测字符串的结尾呢?是的,如果给定字符串的特定长度,它们都可以解析字符串。与缓冲区类似,缓冲区包含2个字符串,由null分隔。它们可以是任意长度的。但它们总是从到。所以to:'thistle first string',from:'this the second string'
no,不使用内置缓冲区。我正在寻找更像python结构的东西,但结果是一个object.nope,而不是内置缓冲区。我正在寻找更像python结构的东西,但结果是一个对象。