JavaScript 简单的BitConverter

JavaScript simple BitConverter

我需要为 JavaScript 制作简单的 C# BitConverter。我制作了简单的 BitConverter

class BitConverter{
constructor(){}
GetBytes(int){
    var b = new Buffer(8)
    b[0] = int;
    b[1] = int >> 8
    b[2] = int >> 16
    b[3] = int >> 24
    return b
}
ToInt(buffer){
    return buffer[0] | buffer[1]<<8 | buffer[2] << 16 | buffer[3] << 24 
}
}

GetBytes 给我的输出与 c# 相同,但 toInt 不是这样...... toInt 不要把我放入 GetBytes 的东西还给我(更大的数字) 示例:

var a = new BitConverter()
var e = 285128170;
var c =a.GetBytes(e);
var v = a.ToInt(c);
console.log(e) // 2851281703
console.log(c) // <Buffer 27 1b f3 a9 00 00 00 00>
console.log(v) //-1443685593

Javascript 将您的最终结果视为带符号的数字。您可以通过使用 >>> 0 结束按位运算来解决此问题,这将强制符号位为 0。因此对于您的示例:

class BitConverter{
    GetBytes(int) {
        var b = new Buffer(8)
        b[0] = int;
        b[1] = int >> 8
        b[2] = int >> 16
        b[3] = int >> 24
        return b
    }
    ToInt(buffer) {
        return (buffer[0] | buffer[1]<<8 | buffer[2] << 16 | buffer[3] << 24) >>> 0;
    }
}

var converter = new BitConverter();
converter.ToInt(converter.GetBytes(2851281703)) // Returns 2851281703

来自documentation of zero-fill right shift

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative.

强调我的。