我从C#tcp服务器获取数据,该服务器向我发送了字符串。该字符串以长度为前缀,一次编码为整数7位。
我如何解析node.js中的长度
答案 0 :(得分:0)
我的解决方案:
function ReadSharpString(buffer)
{
let length = 0, shift = 0, offset = 0;
let byte;
do
{
byte = buffer[offset++];
length |= (byte & 0x7F) << shift;
shift += 7;
}
while (byte >= 0x80);
this.length = () => {
return length;
};
this.toBuffer = () => {
return buffer.slice(offset, offset + length)
};
this.toString = () => {
return this.toBuffer().toString()
};
}
示例:
let string = new ReadSharpString(new Buffer([9,87,45,68,45,87,45,87,45,87]));
的console.log(string.toBuffer());
的console.log(string.toString());
的console.log(string.length减());