4

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]

2
  • 1
    do you have some examples? Commented Feb 18, 2020 at 9:31
  • @NinaScholz Yes, As input i am providing as : ['10100100','11100001','11001','100000','100001','101010','1000111','11011000','1010011','1011000','10111011','10000110','10111010','1110101','1111','110111'] Output what i am trying to get is : [-92, -31, 25, 32, 33, 42, 71, -40, 83, 88, -69, -122, -70, 117, 15, 55] What i am getting as : [-92, -31, -7, -32, -31, -22, -57, -40, -45, -40, -69, -122, -70, -11, -1, -9] Commented Feb 18, 2020 at 9:37

1 Answer 1

4

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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.