JavaScript simple BitConverter

2020-01-19 04:55发布

问题:

I need to make simple C# BitConverter for JavaScript. I made simple 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 is giving me same output as c# but toInt not so ... toInt don't give me back what I've put into GetBytes (bigger numbers) example :

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

回答1:

Javascript is treating your final result as a signed number. You can fix this by ending your bitwise operation with a >>> 0, which will force the sign bit to be 0. So for your example:

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

From the 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.

Emphasis mine.