3 ms·
How does this actually work? Both the post and MDN state that each bit in the 32 bit representation is inverted, resulting in: 5 => 0000000000000000000000000
by gushogg-blake 3y ago
How does this actually work? Both the post and MDN state that each bit in the 32 bit representation is inverted, resulting in:
5 => 00000000000000000000000000000101
~5 => 11111111111111111111111111111010
But parseInt("11111111111111111111111111111010", 2) is 4,294,967,290, not -6. (Even if the first bit were interpreted as the sign, shouldn't this be -2,147,483,642?)
- gushogg-blake 3y agoOK here's how I think it works: from the wikipedia page on two's complement[1], the sign bit is the bit directly to the left of the most significant bit (not the first bit in the 32 bit representation), giving: 5 => 0101 And the only way I can get this to give -6 is if the bitwise NOT operator takes this entire representation (0101), inverts the bits, then creates a new sign bit and inverts that, giving: ~5 => 11010 [1]: https://en.wikipedia.org/wiki/Two's_complement https://en.wikipedia.org/wiki/Two's_complement
- pzmarzly 3y ago> (Even if the first bit were interpreted as the sign, shouldn't this be -2,147,483,642?) No, in two-complement (U2) encoding, negative numbers "start from the top". This lets CPUs have same addition and subtraction instructions for signed and unsigned integers, and rely on overflows to get correct value. E.g. (-1)_i8 + 2_i8 = b11111111 + b00000010 = b(1)00000001 = 1
- gushogg-blake 3y agoAh yes that makes sense. Always assumed the sign bit was just a flag.