protobuf.js使用uint64类型超过16位长度decode的bug

protobuf.js使用uint64类型超过16位长度decode的bug

原版在这里:

https://www.npmjs.com/package/protobufjs

 

protobuf-library.js里有个LongBits的原型toNumber是这样写的:

LongBits.prototype.toNumber = function toNumber(unsigned) {
    if (!unsigned && this.hi >>> 31) {
        var lo = ~this.lo + 1 >>> 0,
            hi = ~this.hi >>> 0;
        if (!lo)
            hi = hi + 1 >>> 0;
        return -(lo + hi * 4294967296);
    }
    return this.lo + this.hi * 4294967296;
};

我一步步查到

this.lo + this.hi * 4294967296;

的时候发现精度有问题

搜了好久发现了一个BigInt解决这个问题

修改后如下:

LongBits.prototype.toNumber = function toNumber(unsigned) {
    if (!unsigned && this.hi >>> 31) {
        var lo = ~this.lo + 1 >>> 0,
            hi = ~this.hi >>> 0;
        if (!lo)
            hi = hi + 1 >>> 0;
        return -(lo + hi * 4294967296);
    }
    return (BigInt(this.lo) + BigInt(this.hi * 4294967296)).toString();
};

proto_bundle.min文件搜索

this.lo+4294967296*this.hi

进行替换

(BigInt(this.lo)+BigInt(4294967296*this.hi)).toString()

 

protobuf-library.min文件搜

this.lo+this.hi*4294967296

进行替换

(BigInt(this.lo)+BigInt(this.hi*4294967296)).toString()

 

 

解决方案2:

protobuf-library.js开头引用

let bigIntXXX;
if(!window.bigInt) {
    bigIntXXX = require("./BigInteger.js");
}
else {
    bigIntXXX = bigInt;
}

 

LongBits.prototype.toNumber修改为

LongBits.prototype.toNumber = function toNumber(unsigned) {
                if (!unsigned && this.hi >>> 31) {
                    var lo = ~this.lo + 1 >>> 0,
                        hi = ~this.hi >>> 0;
                    if (!lo)
                        hi = hi + 1 >>> 0;
                    return -(lo + hi * 4294967296);
                }
                let xxx = bigIntXXX(this.lo.toString()).add(bigIntXXX(this.hi.toString()).multiply(4294967296));
                return xxx.toString();
            };

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值