views:

266

answers:

1

Thanks to everyone in advance -

alert((~1).toString(2));

outputs: -10

but in PHP/Java it outputs 11111111111111111111111111111110

Am I missing something, why does Javascript add a "-" to the output?

Thx, Sam

+4  A: 

I know Java uses two's complement to represent negative numbers, and 11111111111111111111111111111110 in binary, which is what ~1 gives, represents -2. Or, represented in binary with a negative sign, -10, which is what you got.

The way you calculate the negative of 10 (in base 2) using two's complement is that you first invert all of the bits, giving you:

11111111111111111111111111111101

then you add 1, giving you:

11111111111111111111111111111110

I guess the same is happening in Javascript.

IRBMe
In JavaScript, ~1 is -2. -2 in binary is -10.
Nosredna
Yes. https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Bitwise_Operators
Chetan Sastry
So basically the output that I am getting in java/php is 2's complement of -2? If i was working with that number doing something like: alert(parseInt("11111111111111111111111111111110", 2)); I get "4294967294", so this sort of implies that you have to know that the number is in 2's complement before hand?Thanks again!
You can't tell if a binary number represents a signed or an unsigned number. In fact, you can't tell if it represents an integer, a floating point number or anything else. The way you know how to interpret a binary number is by the type of the variable that it's stored in.
IRBMe