문제

In javascript the tilde operator is a bitwise NOT or complement, so why does the following not work as expected?

var x = true;
var tildeX = ~x;
var exclX = !x;


tildeX == exclX; // returns false
도움이 되었습니까?

해결책

The reason is because true is equivalent to 1, and when you perform a bitwise NOT (~) on the number 1 you get -2. Which when combined with the NOT operator (!) will produce false (because the only number that will produce true when combined with the NOT operator is 0)

Here is some information that you might find interesting

Quoted from the link:

Bitwise NOTing any number x yields -(x + 1)

다른 팁

~ is a bitwise operation:

~(true) = ~1 = 0b11111110 (with 8bit character)

! is boolean negation:

!(true) = !1 = 0b00000000

x is not a boolean type and therefore has a load of leading bits set to zero.

~x will convert all those leading bits to 1. Therefore it will be non-zero.

!x, on the other hand, is zero.

That's why tildeX == exclX compares false.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top