16

I was just messing with random stuff, while I found something interesting..

if I have ~ before a number, for example I have tried

~110100100 // result will be  " -110100101 "
~11 // result will be " -12 "

is it making it negative and reducing it by 1? I don't have any idea, can anyone pleas explain this??

Adarsh Hegde
  • 623
  • 2
  • 7
  • 19

1 Answers1

43

The operator ~ returns that result:

~N = -(N+1)

But this is an effect of inverting the value of all bits of a variable.

Double tilde ~~ is used to convert some types to int, since ~ operator converts the value to a 32-bit int before inverting its bits. Thus:

~~'-1' = -1
~~true = 1
~~false = 0
~~5.6 = 5
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
Joanvo
  • 5,677
  • 2
  • 25
  • 35