JavaScript simple BitConverter

爷,独闯天下 提交于 2019-12-13 10:48:47

问题


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.



来源:https://stackoverflow.com/questions/49951290/javascript-simple-bitconverter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!