究竟做了什么? [英] What exactly does ~ do?

查看:95
本文介绍了究竟做了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时在代码中看到符号。我用 ~1 尝试了它,它显示 0
因此,我可以看到一些代码使用这个技巧:

I see sometimes the symbol ~ in code. I tried it with ~1, and it shows 0. And thus, I can see some code using this trick:

if ( !~text.indexOf('a') ){ }

检查真值。它有点变化吗?

To check for truthy value. Is it kind of bit shifting?

推荐答案

这是按位NOT运算符。它会将操作数转换为32位整数,然后产生一个补码(每个都反转)该整数。)

It's the bitwise NOT operator. It will convert the operand to an 32-bit integer, then yields one's complement (inverts every bit) of that integer.

最后,将返回 true 当且仅当该操作的结果是 0 时。

Finally, ! will return true if and only only if the result of that operation is 0.

一些例子可能会有所帮助:

Some examples might help:

  x |   x (bin) | ~x (bin)  |  ~x |   !~x
 -3 | 1111…1101 | 0000…0010 |   2 | false
 -2 | 1111…1110 | 0000…0001 |   1 | false
 -1 | 1111…1111 | 0000…0000 |   0 |  true
  0 | 0000…0000 | 1111…1111 |  -1 | false
  1 | 0000…0001 | 1111…1110 |  -2 | false

换句话说,

if ( !~text.indexOf('a') ) { }

相当于:

if ( text.indexOf('a') == -1 ) { }

这篇关于究竟做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆