Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a two's complement string to a number

Tags:

javascript

I have binary form for -3 in two's complement form - 11111111111111111111111111111101, and use it with parseInt function:

parseInt('11111111111111111111111111111101', 2)

But it returns 4294967293, which is the integer that results if 11111111111111111111111111111101 is parsed as unsigned int. How can I parse integer as a signed one?

like image 954
Max Koretskyi Avatar asked May 04 '16 08:05

Max Koretskyi


People also ask

How do you find the complement of a number 2s?

Two's complement is the way every computer I know of chooses to represent integers. To get the two's complement negative notation of an integer, you write out the number in binary. You then invert the digits, and add one to the result.


2 Answers

~~parseInt('11111111111111111111111111111101',2)// == -3

is what you are looking for.

Related answer ~~ vs-parseint

var x = ~~y; is a 'trick' (similar to var x = y << 0;) that (ab)uses the unary bitwise NOT operator to force the result to be in the range of a signed 32-bit integer, discarding any non-integer portion.

like image 195
Tschallacka Avatar answered Oct 01 '22 16:10

Tschallacka


i had the same problem, you can use the following:

function parseInt2complement(bitstring,bitcount)
{
    value = parseInt(bitstring, 2);

    if ((value & (1<<(bitcount-1))) > 0) {
       value = value - (1<<(bitcount));
    }
    return value;
}

console.log(parseInt2complement('111111111111111111111111111101', 30))
console.log(parseInt2complement('1111111111111111111111111111101', 31))
like image 28
MatSch Avatar answered Oct 01 '22 16:10

MatSch