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?
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.
~~parseInt('11111111111111111111111111111101',2)// == -3
is what you are looking for.
Related answer ~~ vs-parseint
var x = ~~y;
is a 'trick' (similar tovar 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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With