Getting decimal from binary's signed 2's complement

Prashant Kumar Sharma :

I am trying to get decimal number for binary's signed 2's complement if it is available for the same.

Here is how am i trying to do it.

    function getSignedInteger(bits) {
        for (var i = 0; i < bits.length; i++) {
            bits[i]
        }
        let negative = (bits[0] === '1');
        console.log(bits[0] === '1')
        if (negative) {
            let inverse = '';
            for (let i = 0; i < bits.length; i++) {
                inverse += (bits[i] === '0' ? '1' : '0');
            }
            console.log(inverse)
            return (parseInt(inverse, 2) + 1) * -1;
        } else {
            return parseInt(bits, 2);
        }
    }

Input : ['10100100','11100001','11001','100000','100001','101010','1000111','11011000','1010011','1011000','10111011','10000110','10111010','1110101','1111','110111']

Output : [-92, -31, 25, 32, 33, 42, 71, -40, 83, 88, -69, -122, -70, 117, 15, 55]

What actually i am getting [-92, -31, -7, -32, -31, -22, -57, -40, -45, -40, -69, -122, -70, -11, -1, -9]

Nina Scholz :

You could add a check for value it has the sign bit at the first bit and take either

  • the delta of the parsed value and 256, or
  • the parsed number.

function getSignedInteger(bits) {
    var value = parseInt(bits, 2);
    return value & (1 << 7)
        ? value - (1 << 8)
        : value;
}
console.log(...['10100100', '11100001', '11001', '100000', '100001', '101010', '1000111', '11011000', '1010011', '1011000', '10111011', '10000110', '10111010', '1110101', '1111', '110111'].map(getSignedInteger));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7174&siteId=1