Skip to content Skip to sidebar Skip to footer

Javascript Simple Bitconverter

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

Solution 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:

classBitConverter{
    GetBytes(int) {
        var b = new Buffer(8)
        b[0] = int;
        b[1] = int >> 8
        b[2] = int >> 16
        b[3] = int >> 24return 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.

Post a Comment for "Javascript Simple Bitconverter"