user2101
user2101

Reputation: 47

How does bitwise signed symbol work ~

So, I've looked at several websites and still don't understand what the bitwise operator ~ does. Basically, I understand that for a number such as 4 which would be represented in binary as 100 should be flipped when you put ~4 to 011; however, there appears to be somehow become -5 then the tutorials say something about a 32-bit representation with a load a negative digit number. At this point I am completely lost please explain how ~ works.

Upvotes: 2

Views: 88

Answers (2)

Pointy
Pointy

Reputation: 413757

The number 4 is not 100. It's 00000000000000000000000000000100. All those zeros are flipped to ones by ~.

The resulting number is negative because of how those 32-bit values are interpreted when converted back to ordinary JavaScript numbers. But I'm getting ahead of myself: the first thing a bitwise operator in JavaScript does is create a temporary 32-bit integer value from the source number. Then the operator does its magic, which in the case of ~ is to invert all the bits of that 32-bit value. Then the number is converted back to a 64-bit double-precision floating point value, which is the normal JavaScript numeric type.

The 32-bit values are interpreted as signed values, which has to do with the way computer arithmetic works. Suffice to say that any 32-bit value whose left-most (most significant) bit is a 1 is interpreted as a negative value.

Binary math and the way modern computers (well, almost all historical ones too) do it is kind-of a broad subject. Some programming languages provide abstractions that mostly hide the realities of how the computing hardware actually works; JavaScript is not really one of those languages in most implementations.

Upvotes: 3

RobIII
RobIII

Reputation: 8821

4 = 00000000 00000000 00000000 00000100

~4 = 11111111 11111111 11111111 11111011

Since the leftmost bit is the sign bit in a signed 32 bit value that's where your negative values come from. Slightly related: you may also want to read up on MSB, LSB.

Upvotes: 3

Related Questions