Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Javascript treat a number as a two's complement

Here is the explanation of why ~5 equals to -6 from here:

5 = 0000 0101

Flipped (~5) = 1111 1010

So, which number does 1111 1010 represent? Since the first digit is a 1 we know it's a negative value. To find which value, do

-(flip(1111 1010) + 1) = -(0000 0101 + 1) -(0000 0110) = -6

I'm wondering why Javascript treats the result of the ~5 as a number in the two's complement form?

My confusion stems from the fact that if I write 0b11111010 in the console it evaluates to 250, not -6

like image 222
Max Koretskyi Avatar asked Oct 21 '25 17:10

Max Koretskyi


1 Answers

Because that's how Javascript represents negative numbers in binary. Docs:

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format. Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, a.k.a. ones' complement of the number) plus one.

like image 182
p4sh4 Avatar answered Oct 23 '25 05:10

p4sh4