什么时候应该使用按位运算符? [英] When should I use a bitwise operator?

查看:298
本文介绍了什么时候应该使用按位运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了以下堆栈溢出问题,并且了解按位与逻辑之间的区别.

I read the following Stack Overflow questions, and I understand the differences between bitwise and logical.

参考-此符号是什么意思在PHP中?

但是,它们都没有解释我何时应该使用按位或逻辑.

However, none of them explains when I should use bitwise or logical.

何时应该使用按位运算符而不是逻辑运算符,反之亦然?

When should I use bitwise operators rather than logical ones and vice versa?

在哪种情况下我需要一点一点地比较?

In which situation do I need to compare bit by bit?

我不是在问差异,而是在需要使用按位运算符时的情况.

I am not asking about the differences, but I am asking the situation when you need to use bitwise operators.

推荐答案

按位|&与逻辑||&&完全不同..

Bitwise | and & and logical || and && are totally different.

按位运算符对两个数字的 bits 执行运算并返回结果.这意味着这不是肯定或否定的事情.如果在条件语句中使用它们,则通常将它们用作逻辑比较的一部分.例如:

Bitwise operators perform operations on the bits of two numbers and return the result. That means it's not a yes or no thing. If they're being used in conditional statements, they're often used as part of logical comparisons. For example:

if ($x & 2 == 2) {
    // The 2^1 bit is set in the number $x
}

逻辑运算符比较两个(或多个)条件/表达式并返回true或false.您通常在条件语句(例如ifwhile)中使用它们.例如:

Logical operators compare two (or more) conditions/expressions and return true or false. You use them most commonly in conditional statements, like if and while. For example:

if ($either_this || $or_this) {
    // Either expression was true
}

这篇关于什么时候应该使用按位运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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