简体   繁体   English

Node.js 和 64 位变量

[英]Node.js and 64-bit varints

I'm in the process of writing a Node.js based application which talks via TCP to a C++ based server.我正在编写一个基于 Node.js 的应用程序,该应用程序通过 TCP 与基于 C++ 的服务器通信。 The server speaks a binary protocol, quite similar to Protocol Buffers, but not exactly the same.服务器使用二进制协议,与 Protocol Buffers 非常相似,但不完全相同。

One data type the server returns is that of a unsigned 64-bit integer (uint64_t), serialized as a varint, where the most significant bit is used to indicate whether the next byte is also part of the int.服务器返回的一种数据类型是无符号 64 位整数 (uint64_t),序列化为 varint,其中最高有效位用于指示下一个字节是否也是 int 的一部分。

I am unable to parse this out in Javascript currently due to the 32-bit limitation on bitwise operations, and also the fact that JS doesn't do 64-bit ints natively.由于按位运算的 32 位限制,以及 JS 本身不执行 64 位整数的事实,我目前无法在 Javascript 中解析它。 Does anyone have any suggestions on how I could do this?有没有人对我如何做到这一点有任何建议?

My varint reading code is very similar to that shown here: https://github.com/chrisdickinson/varint/blob/master/decode.js我的 varint 读取代码与此处显示的非常相似: https : //github.com/chrisdickinson/varint/blob/master/decode.js

I thought I could use node-bignum to represent the number, but I'm unsure how to turn a Buffer consisting of varint bytes into this.我以为我可以使用node-bignum来表示数字,但是我不确定如何将包含 varint 字节的 Buffer 转换为这个数字。

Cheers, Nathan干杯,内森

Simply took the existing varint read module and modified it to yield a Bignum object instead of a regular number:简单地使用现有的 varint 读取模块并修改它以产生一个 Bignum 对象而不是一个常规数字:

Bignum = require('bignum');
module.exports = read;

var MSB = 0x80
    , REST = 0x7F;

function read(buf, offset) {
    var res    = Bignum(0)
        , offset = offset || 0
        , counter = offset
        , b
        , shift  = 0
        , l = buf.length;

    do {
        if(counter >= l) {
            read.bytesRead = 0;
            return undefined
        }
        b = buf[counter++];
        res = res.add(Bignum(b & REST).shiftLeft(shift));
        shift += 7
    } while (b >= MSB);

    read.bytes = counter - offset;

    return res
}

Use it exactly the same way as you would have used the original decode module.以与使用原始解码模块完全相同的方式使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM