在整数上使用逻辑运算符

发布于 2025-02-08 23:43:32 字数 1399 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

这样的小城市 2025-02-15 23:43:32

十进制1000是二进制111110 1000。十进制255是二进制1111 1111。首先,它们被转换为签名的int,通常为32位。

服用&设置了设置操作数的所有位置的位置:

  0000 0000 0000 0000 0000 0011 1110 1000
  0000 0000 0000 0000 0000 0000 1111 1111
& ---------------------------------------
  0000 0000 0000 0000 0000 0000 1110 1000

这是十进制的232。服用|将在所有位置设置位置至少设置了一位,即IE会产生二进制11111111,即十进制1023。服用^将在所有位置设置的所有位置设置了其中一个位,即

  0000 0000 0000 0000 0000 0011 1110 1000
  0000 0000 0000 0000 0000 0000 1111 1111
^ ---------------------------------------
  0000 0000 0000 0000 0000 0011 0001 0111

&&不是二进制操作。仅当两个操作数均不为零时,它才会返回1。 ||在且仅当操作数中的至少一个非零时返回1。在其他情况下,它们分别返回0。

Decimal 1000 is binary 11 1110 1000. Decimal 255 is binary 1111 1111. First, they are converted to signed int, which is usually 32 bits wide.

Taking & of them sets the bit at all positions where both bits of the operands are set:

  0000 0000 0000 0000 0000 0011 1110 1000
  0000 0000 0000 0000 0000 0000 1111 1111
& ---------------------------------------
  0000 0000 0000 0000 0000 0000 1110 1000

This is decimal 232. Taking | would have set the bit at all positions where at least one bit is set, i.e. would have produced binary 11 1111 1111, which is decimal 1023. Taking ^ would have set the bit at all positions where exactly one of the bits is set, i.e.

  0000 0000 0000 0000 0000 0011 1110 1000
  0000 0000 0000 0000 0000 0000 1111 1111
^ ---------------------------------------
  0000 0000 0000 0000 0000 0011 0001 0111

&& is not a binary operation. It simply returns 1 if and only if both operands are non-zero. || returns 1 if and only if at least one of the operands is non-zero. In other cases, they return 0, respectively.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文